description.ts
This file
Path
packages/project/src/description.ts
347 lines · 9.5 KiB · TypeScript
Last changed by
Merge redesign into mainoscabrielbefore adoptioncaedd21
History of this fileTake it
Merge redesign into mainoscabrielbefore adoptioncaedd21
lines 1–347why, one step back1/**2 * A project's one line, read from its README on main: the first paragraph of3 * prose, its markup dropped, cut to the cap. A project's config has no field4 * for it, so the README is the one source. A list reads it with the count of5 * landings the project's record keeps, and keeps both until the next landing.6 */7import type { RepoHost, RepoNotFound } from "@repo/artifacts/repo-host";8import {9 PROJECT_DESCRIPTION_CAP,10 ProjectDescription,11} from "@repo/protocol/domain/front-page";12import type { ProjectListing } from "@repo/protocol/domain/front-page";13import type { ProjectName } from "@repo/protocol/ids";14import type { UnknownPath, UnknownRevision } from "@repo/protocol/refusal";15import {16 Array as Arr,17 Cause,18 Context,19 DateTime,20 Effect,21 Option,22 Schema,23} from "effect";2425import { codeProjectOf, treeOf } from "./code.ts";26import type { CodeProject } from "./code.ts";27import { contentsOf } from "./code/file.ts";28import type { ProjectApi } from "./project.ts";2930const FENCE = /^\s{0,3}(?:`{3,}|~{3,})/u;3132const HEADING = /^\s{0,3}#{1,6}(?:\s|$)/u;3334const RULE = /^\s{0,3}(?:[=\-~^*#+_]\s*){3,}$/u;3536const SETEXT = /^\s{0,3}(?:=+|-+)\s*$/u;3738const INDENTED = /^(?: {4}|\t)/u;3940const LIST_ITEM = /^\s{0,3}(?:[-*+]|\d{1,9}[.)])\s/u;4142const TABLE = /^\s*\|/u;4344const DEFINITION = /^\s{0,3}\[[^\]]+\]:\s/u;4546const DIRECTIVE = /^\.\.(?:\s|$)/u;4748const QUOTE = /^\s{0,3}>\s?/u;4950const ENTITIES: ReadonlyMap<string, string> = new Map([51 ["&", "&"],52 ["<", "<"],53 [">", ">"],54 [""", '"'],55 ["'", "'"],56 ["'", "'"],57 [" ", " "],58]);5960const decodeDescription = Schema.decodeOption(ProjectDescription);6162/** The blocks between blank lines, with fenced code and HTML comments left out. */63const blocksOf = (text: string): readonly (readonly string[])[] => {64 const blocks: string[][] = [];65 let current: string[] = [];66 let fenced = false;6768 const close = () => {69 if (current.length > 0) {70 blocks.push(current);71 }7273 current = [];74 };7576 const uncommented = text.replaceAll(/<!--[\s\S]*?-->/gu, "");7778 for (const line of uncommented.split(/\r?\n/u)) {79 if (FENCE.test(line)) {80 close();81 fenced = !fenced;82 } else if (!fenced) {83 if (line.trim() === "") {84 close();85 } else {86 current.push(line);87 }88 }89 }9091 close();9293 return blocks;94};9596/** The block's lines of prose, its headings, rules and titles' underlines dropped. */97const proseOf = (block: readonly string[]): readonly string[] => {98 const [first = ""] = block;99100 if (101 INDENTED.test(first) ||102 LIST_ITEM.test(first) ||103 TABLE.test(first) ||104 DIRECTIVE.test(first)105 ) {106 return [];107 }108109 const kept: string[] = [];110111 for (const line of block) {112 if (SETEXT.test(line) || RULE.test(line)) {113 // The line above an underline is a title.114 kept.pop();115 } else if (!HEADING.test(line) && !DEFINITION.test(line)) {116 kept.push(line.replace(QUOTE, ""));117 }118 }119120 return kept;121};122123const plainOf = (markup: string): string =>124 markup125 .replaceAll(/!\[[^\]]*\](?:\([^)]*\)|\[[^\]]*\])/gu, "")126 .replaceAll(/\[(?<text>[^\]]*)\](?:\([^)]*\)|\[[^\]]*\])/gu, "$<text>")127 .replaceAll(/<[^>]*>/gu, " ")128 .replaceAll(/&(?:[a-z]+|#\d+);/gu, (entity) => ENTITIES.get(entity) ?? " ")129 .replaceAll(/\*\*|__|`+/gu, "")130 .replaceAll(/(?<lead>^|[\s(])[*_](?=\S)/gu, "$<lead>")131 .replaceAll(/(?<=\S)[*_](?=[\s).,;:!?]|$)/gu, "")132 .replaceAll(/\s+/gu, " ")133 .trim();134135const graphemes = new Intl.Segmenter("en", { granularity: "grapheme" });136137/** At most the cap, cut at a word with an ellipsis when it runs over. */138const capped = (line: string): string => {139 if (line.length <= PROJECT_DESCRIPTION_CAP) {140 return line;141 }142143 const room = line.slice(0, PROJECT_DESCRIPTION_CAP);144 const word = room.lastIndexOf(" ");145146 // With no space, drop the last character whole, never half of a surrogate pair or an emoji's sequence.147 const cut =148 word > 0149 ? room.slice(0, word)150 : room.slice(0, [...graphemes.segment(room)].at(-1)?.index ?? 0);151152 return `${cut.replace(/[\s,;:.!?-]+$/u, "")}…`;153};154155/** None when the README holds no paragraph of prose. */156export const descriptionOf = (157 readme: string158): Option.Option<ProjectDescription> => {159 for (const block of blocksOf(readme)) {160 const plain = plainOf(proseOf(block).join(" "));161162 if (/[\p{L}\p{N}]/u.test(plain)) {163 return decodeDescription(capped(plain));164 }165 }166167 return Option.none();168};169170/**171 * What a list read of a landed project, and the landing it read at: the172 * description from the README on main, and how many landings the project's173 * record keeps. Both move only by a landing.174 */175export interface KeptDescription {176 readonly landedAt: DateTime.Utc;177 readonly landings: number;178 readonly description?: ProjectDescription;179}180181/** Where a list reads a landed project: its main, and its record's count of landings. */182export interface LandedProject {183 readonly code: CodeProject;184 readonly landingCount: Effect.Effect<number>;185}186187export const landedProjectOf = (188 api: ProjectApi,189 project: ProjectName190): LandedProject => ({191 code: codeProjectOf(api, project),192 landingCount: api.landingCount(),193});194195export interface ProjectDescriptionsApi {196 readonly get: (197 projects: readonly ProjectName[]198 ) => Effect.Effect<ReadonlyMap<ProjectName, KeptDescription>>;199 readonly put: (200 entries: ReadonlyMap<ProjectName, KeptDescription>201 ) => Effect.Effect<void>;202}203204/** The default keeps nothing, so every list reads each landed project's README. */205export const ProjectDescriptions = Context.Reference<ProjectDescriptionsApi>(206 "project/ProjectDescriptions",207 {208 defaultValue: () => ({209 get: () => Effect.succeed(new Map()),210 put: () => Effect.void,211 }),212 }213);214215const READS_AT_ONCE = 8;216217const orWarn = <A, E, R>(218 effect: Effect.Effect<A, E, R>,219 fallback: A,220 warning: string221): Effect.Effect<A, never, R> =>222 Effect.catchCause(effect, (cause) =>223 Cause.hasInterruptsOnly(cause)224 ? Effect.interrupt225 : Effect.as(Effect.logWarning(warning, cause), fallback)226 );227228const readmeDescription = (229 code: CodeProject230): Effect.Effect<231 Option.Option<ProjectDescription>,232 UnknownRevision | UnknownPath | RepoNotFound,233 RepoHost234> =>235 Effect.gen(function* () {236 const { readme } = yield* treeOf(code, Option.none(), Option.none());237238 if (readme === undefined) {239 return Option.none();240 }241242 const contents = yield* contentsOf(code.repo, readme.sha);243244 return Option.flatMap(245 Option.flatMap(contents, ({ text }) => text),246 descriptionOf247 );248 });249250const sameLanding = (251 kept: KeptDescription,252 landedAt: DateTime.Utc | undefined253) => landedAt !== undefined && DateTime.Equivalence(kept.landedAt, landedAt);254255const keptOf = (256 landedAt: DateTime.Utc,257 landings: number,258 description: Option.Option<ProjectDescription>259): KeptDescription =>260 Option.match(description, {261 onNone: () => ({ landedAt, landings }),262 onSome: (found) => ({ description: found, landedAt, landings }),263 });264265const readLanded = (266 { code, landingCount }: LandedProject,267 landedAt: DateTime.Utc268) =>269 Effect.map(270 Effect.all([readmeDescription(code), landingCount]),271 ([description, landings]) => keptOf(landedAt, landings, description)272 );273274const listedWith = (275 listing: ProjectListing,276 { description, landings }: KeptDescription277): ProjectListing =>278 description === undefined279 ? { ...listing, landings }280 : { ...listing, description, landings };281282/**283 * Main and the count of landings move only by a landing, so what a list read284 * while a project's last landing stands is kept until the next one. A project285 * not yet landed has no main to read.286 */287export const withDescriptions = <E>(288 listed: readonly ProjectListing[],289 landedOf: (project: ProjectName) => Effect.Effect<LandedProject, E>290): Effect.Effect<readonly ProjectListing[], never, RepoHost> =>291 Effect.gen(function* () {292 const landed = listed.flatMap(({ landedAt, project }) =>293 landedAt === undefined ? [] : [{ landedAt, project }]294 );295296 if (landed.length === 0) {297 return listed;298 }299300 const store = yield* ProjectDescriptions;301302 const kept = yield* orWarn(303 Effect.suspend(() =>304 store.get(Arr.dedupe(landed.map(({ project }) => project)))305 ),306 new Map<ProjectName, KeptDescription>(),307 "the kept descriptions were not read: every landed project is read"308 );309310 const stale = landed.filter(({ landedAt, project }) => {311 const entry = kept.get(project);312313 return entry === undefined || !sameLanding(entry, landedAt);314 });315316 const read = yield* Effect.forEach(317 stale,318 ({ landedAt, project }) =>319 orWarn(320 Effect.suspend(() => landedOf(project)).pipe(321 Effect.flatMap((source) => readLanded(source, landedAt)),322 Effect.map((entry) => Option.some([project, entry] as const))323 ),324 Option.none(),325 `${project} was not read: it is listed with no description and no count of landings`326 ),327 { concurrency: READS_AT_ONCE }328 );329330 const found = new Map<ProjectName, KeptDescription>(Arr.getSomes(read));331332 if (found.size > 0) {333 yield* orWarn(334 Effect.suspend(() => store.put(found)),335 undefined,336 "the descriptions read were not kept"337 );338 }339340 return listed.map((listing): ProjectListing => {341 const entry = found.get(listing.project) ?? kept.get(listing.project);342343 return entry === undefined || !sameLanding(entry, listing.landedAt)344 ? listing345 : listedWith(listing, entry);346 });347 });