Skip to content
Myr

Merge branch 'build/903-code-reads'

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by oscabriel · committed by oscabriel · parents 254268a, 623b096 · Browse files · 23 files+3243 added−108 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

23 files+3243 added−108 removed

  • tests:+1650 added−53 removed
  • other:+1593 added−55 removed

23 files+3243 added−108 removed

modified:apps/platform/src/ports.ts+15 added-1 removed
modified:apps/platform/src/raw.ts+10 added-7 removed
modified:apps/platform/src/surfaces.ts+6 added-5 removed
1 unmodified line
2import { platformSkill } from "@repo/agent-kit/platform";3import { RepoHost } from "@repo/artifacts/repo-host";4import { Brand } from "@repo/brand";5import { Upstream } from "@repo/git/upstream";6import { CodeCache } from "@repo/project/code/cache";7import { FrontPage } from "@repo/project/front-page";8import { Projects } from "@repo/project/projects";9import { authenticated, bearerToken } from "@repo/protocol/authenticate";10import { Client, Contracts, surfaced } from "@repo/protocol/contracts";
375 unmodified lines
386387/** `/<project>/raw/<rev>/<path…>`: a project's raw files (`raw.ts`). */388const raw = HttpRouter.use((router) =>389 Effect.gen(function* () {390 // The isolate's code cache, as the `/rpc` code reads have it: a391 // `Context.Reference`, so without it every raw read goes to Artifacts.392 const services = Context.make(RepoHost, yield* RepoHost).pipe(390 Context.add(Projects, yield* Projects)393 Context.add(Projects, yield* Projects),394 Context.add(CodeCache, yield* CodeCache)395 );396397 yield* router.add("GET", "/:project/raw/*", (request) =>398 Effect.gen(function* () {
3 unmodified lines
402 onNone: () =>403 Effect.succeed(HttpServerResponse.empty({ status: 404 })),404 onSome: (project) =>405 fromWeb((web) =>402 Effect.provide(403 rawResponse(web, project, params["*"] ?? ""),404 services405 )406 Effect.provide(rawResponse(web, project), services)407 )(request),408 });409 })410 );
75 unmodified lines
added:apps/platform/test/code-reads.test.ts+177 added
1/**2 * The code reads over `/rpc`, as anyone not signed in calls them: datekit's3 * refs, a folder, a file, the log and a commit's changes, read from its4 * canonical repo only. No code read's payload names a repo, so a caller5 * cannot point one at a fork: an extra `repo` key is dropped or refused,6 * and the canonical repo is read either way.7 */8import { describe, expect, it } from "@effect/vitest";9import { Contracts } from "@repo/protocol/contracts";10import { RepoName, RepoPath } from "@repo/protocol/ids";11import { advanceTo } from "@repo/testkit/clock";12import { aProject, withAsk, withVouches } from "@repo/testkit/scenarios";13import { Effect, Layer, SchemaAST } from "effect";1415import { Handlers } from "../src/handlers.ts";16import { MemorySessions } from "../src/sessions/memory.ts";17import { seeded, worldOf } from "./handlers.fixtures.ts";18import { origin, rpcClient, served } from "./harness.ts";1920const datekit = aProject({ people: ["bob"] }).pipe(21 withVouches(["bob"]),22 withAsk({ id: "parse-iso", territory: "packages/parser" })23);2425const { project } = datekit;2627/** The platform over datekit's world, seeded: made, pushed to, its ask open. */28const platform = Effect.gen(function* () {29 yield* advanceTo("2026-10-07T12:00:00Z");3031 const world = yield* Layer.build(worldOf([datekit]));3233 yield* seeded(datekit).pipe(Effect.provide(world));3435 const ports = Layer.succeedContext(world);3637 return yield* served(38 Layer.mergeAll(39 Handlers.pipe(Layer.provide(ports)),40 ports,41 MemorySessions.layer({})42 )43 );44});4546/** The contracts that read a project's code. */47const codeReads = [48 "listRefs",49 "readTree",50 "listPaths",51 "readFile",52 "log",53 "showCommit",54 "why",55];5657/** Every field of a payload, nested ones included: its name and its type's AST. */58const fieldsIn = (59 ast: SchemaAST.AST60): readonly (readonly [string, SchemaAST.AST])[] => {61 if (SchemaAST.isObjects(ast)) {62 return ast.propertySignatures.flatMap(({ name, type }) => [63 [String(name), type] as const,64 ...fieldsIn(type),65 ]);66 }6768 return SchemaAST.isUnion(ast) ? ast.types.flatMap(fieldsIn) : [];69};7071describe("the code reads over /rpc", () => {72 it.effect(73 "answer anyone with datekit's refs, its root folder and a file",74 () =>75 Effect.gen(function* () {76 const { handler } = yield* platform;77 const anyone = yield* rpcClient(handler);78 const refs = yield* anyone.listRefs({ project });79 const root = yield* anyone.readTree({ project });8081 const file = yield* anyone.readFile({82 path: RepoPath.make("package.json"),83 project,84 });8586 expect([refs.project, refs.tags]).toStrictEqual([project, []]);87 expect(root.at).toBe(refs.landed);88 expect(root.entries.map(({ name }) => name)).toStrictEqual(89 expect.arrayContaining(["packages", "package.json"])90 );91 expect(file.text).toContain('"name": "datekit"');92 })93 );9495 it.effect("answer anyone with datekit's paths, log and first commit", () =>96 Effect.gen(function* () {97 const { handler } = yield* platform;98 const anyone = yield* rpcClient(handler);99 const { landed } = yield* anyone.listRefs({ project });100 const { commits } = yield* anyone.log({ project });101 const first = commits.at(-1)?.sha ?? "main";102 const paths = yield* anyone.listPaths({ at: first, project });103104 expect([commits[0]?.sha, commits.at(-1)?.subject]).toStrictEqual([105 landed,106 "Start",107 ]);108 expect(paths.paths).toContain("packages/parser/src/parse.ts");109110 const diff = yield* anyone.showCommit({ project, sha: paths.at });111112 expect(113 diff.files.map(({ path, status }) => [path, status])114 ).toStrictEqual(paths.paths.map((path) => [path, "added"]));115 })116 );117118 it.effect(119 "read the canonical repo whatever extra key a payload carries",120 () =>121 Effect.gen(function* () {122 const { handler } = yield* platform;123124 // The wire's request, written as a client would send it, with a125 // `repo` beside the project that no contract has.126 const payload = JSON.stringify({ project, repo: "datekit--me--alice" });127128 const response = yield* Effect.promise(() =>129 handler(130 new Request(`${origin}/rpc`, {131 body: `{"_tag":"Request","id":"1","tag":"readTree","payload":${payload},"headers":[]}`,132 headers: { "content-type": "application/json" },133 method: "POST",134 })135 )136 );137138 const text = yield* Effect.promise(() => response.text());139 const anyone = yield* rpcClient(handler);140 const canonical = yield* anyone.readTree({ project });141142 expect(response.status).toBe(200);143 expect(text).not.toContain("datekit--me--alice");144 expect(text).toContain(canonical.at);145 })146 );147148 it("name no repo in any code read's payload", () => {149 const rpcs = codeReads.map(150 (tag) => [tag, Contracts.requests.get(tag)] as const151 );152153 const fields = rpcs.flatMap(([tag, rpc]) =>154 rpc === undefined155 ? []156 : fieldsIn(rpc.payloadSchema.ast).map(157 ([name, type]) => [tag, name, type] as const158 )159 );160161 expect(162 rpcs.flatMap(([tag, rpc]) => (rpc === undefined ? [tag] : []))163 ).toStrictEqual([]);164 // The check sees a branded field: `readFile`'s path is a `RepoPath`.165 expect(166 fields.some(167 ([tag, name, type]) =>168 tag === "readFile" && name === "path" && type === RepoPath.ast169 )170 ).toBeTruthy();171 expect(172 fields.flatMap(([tag, name, type]) =>173 type === RepoName.ast || name === "repo" ? [`${tag}.${name}`] : []174 )175 ).toStrictEqual([]);176 });177});
added:apps/platform/test/raw.test.ts+239 added
1/**2 * A project's raw files through the platform's fetch handler:3 * `GET /<project>/raw/<rev>/<path…>` answers the bytes with their headers4 * to anyone, a stale bearer token or not; a path that climbs out is a5 * 404; and git's own paths beside it still reach git.6 */7import { describe, expect, it } from "@effect/vitest";8import { RefName, RepoHost } from "@repo/artifacts/repo-host";9import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";10import { CodeCacheLive } from "@repo/project/code/cache";11import { Projects } from "@repo/project/projects";12import { RepoName } from "@repo/protocol/ids";13import { Person } from "@repo/protocol/principal";14import { advanceTo } from "@repo/testkit/clock";15import { gitClient } from "@repo/testkit/git-client";16import { aProject } from "@repo/testkit/scenarios";17import { Context, Effect, Layer, Option, Ref } from "effect";1819import { Handlers } from "../src/handlers.ts";20import { MemorySessions } from "../src/sessions/memory.ts";21import { worldOf } from "./handlers.fixtures.ts";22import { origin, served } from "./harness.ts";2324const datekit = aProject({ people: [] });2526const { project } = datekit;2728const readme = "# datekit\n\nDates, parsed.\n";2930/**31 * The platform over a world where datekit was made and its first commit,32 * a README and a manifest, pushed to main; and that commit's id. With33 * `reads`, the platform has the isolate's code cache, as `ports.ts` gives34 * it, and each tree its repo host is asked for is counted there.35 */36const platformWith = (reads: Option.Option<Ref.Ref<number>>) =>37 Effect.gen(function* () {38 yield* advanceTo("2026-10-07T12:00:00Z");3940 const world = yield* Layer.build(worldOf([datekit]));4142 const first = yield* Effect.gen(function* () {43 const host = yield* RepoHost;44 const api = yield* (yield* Projects).create(project);45 const initializer = Person.make({ handle: datekit.initializer });46 const client = yield* gitClient(memoryFs());4748 yield* api.initProject(initializer, {});4950 const sha = yield* client.commit("Start", [51 ["README.md", readme],52 ["package.json", '{ "name": "datekit" }\n'],53 ]);5455 yield* host.push(RepoName.make(project), client.source, [56 { from: Option.none(), ref: RefName.make("refs/heads/main"), to: sha },57 {58 from: Option.none(),59 ref: RefName.make("refs/tags/@datekit/core@1.0.0"),60 to: sha,61 },62 ]);63 yield* api.recordFirstPush(initializer, sha);6465 return sha;66 }).pipe(Effect.orDie, Effect.provide(world));6768 const cached = yield* Option.match(reads, {69 onNone: () => Effect.succeed(world),70 onSome: (count) =>71 Effect.map(Layer.build(CodeCacheLive(100)), (cache) => {72 const host = Context.get(world, RepoHost);7374 return Context.merge(world, cache).pipe(75 Context.add(76 RepoHost,77 RepoHost.of({78 ...host,79 readTree: (name, tree) =>80 Effect.andThen(81 Ref.update(count, (n) => n + 1),82 host.readTree(name, tree)83 ),84 })85 )86 );87 }),88 });8990 const ports = Layer.succeedContext(cached);9192 const { fetch } = yield* served(93 Layer.mergeAll(94 Handlers.pipe(Layer.provide(ports)),95 ports,96 MemorySessions.layer({})97 )98 );99100 return { fetch, first };101 });102103const platform = platformWith(Option.none());104105const get = (106 fetch: (request: Request) => Effect.Effect<Response>,107 path: string,108 headers: Record<string, string> = {}109) =>110 Effect.flatMap(111 fetch(new Request(`${origin}${path}`, { headers })),112 (response) =>113 Effect.map(114 Effect.promise(() => response.text()),115 (text) => ({ headers: response.headers, status: response.status, text })116 )117 );118119describe("a project's raw files", () => {120 it.effect(121 "answer anyone with the bytes and their headers, a stale bearer or not",122 () =>123 Effect.gen(function* () {124 const { fetch, first } = yield* platform;125 const path = `/${project}/raw/${first}/README.md`;126127 const answers = yield* Effect.forEach(128 [{}, { authorization: "Bearer not-a-token-the-platform-knows" }],129 (headers) =>130 Effect.map(get(fetch, path, headers), (answer) => ({131 cache: answer.headers.get("cache-control"),132 etag: /^"[0-9a-f]{40}"$/u.test(answer.headers.get("etag") ?? ""),133 nosniff: answer.headers.get("x-content-type-options"),134 sandboxed: (135 answer.headers.get("content-security-policy") ?? ""136 ).includes("sandbox"),137 status: answer.status,138 text: answer.text,139 type: answer.headers.get("content-type"),140 }))141 );142143 expect(answers).toStrictEqual(144 answers.map(() => ({145 cache: "public, max-age=31536000, immutable",146 etag: true,147 nosniff: "nosniff",148 sandboxed: true,149 status: 200,150 text: readme,151 type: "text/plain; charset=utf-8",152 }))153 );154 expect(answers).toHaveLength(2);155156 const main = yield* get(fetch, `/${project}/raw/main/README.md`);157158 expect([main.status, main.headers.get("cache-control")]).toStrictEqual([159 200,160 "public, max-age=60",161 ]);162 })163 );164165 it.effect(166 "find a tag by its name, URL-encoded in one segment, slash and all",167 () =>168 Effect.gen(function* () {169 const { fetch } = yield* platform;170171 const answer = yield* get(172 fetch,173 `/${project}/raw/${encodeURIComponent("@datekit/core@1.0.0")}/README.md`174 );175176 expect([177 answer.status,178 answer.text,179 answer.headers.get("cache-control"),180 ]).toStrictEqual([200, readme, "public, max-age=60"]);181 })182 );183184 it.effect(185 "is a 404 with no body for a path that climbs out, a missing file or project",186 () =>187 Effect.gen(function* () {188 const { fetch, first } = yield* platform;189190 const answers = yield* Effect.forEach(191 [192 `/${project}/raw/${first}/../../x`,193 `/${project}/raw/${first}/..%2F..%2Fx`,194 `/${project}/raw/${first}/nope.md`,195 `/${project}/raw/v9/README.md`,196 `/nobody/raw/main/README.md`,197 ],198 (path) =>199 Effect.map(get(fetch, path), ({ status, text }) => [status, text])200 );201202 expect(answers).toStrictEqual(answers.map(() => [404, ""]));203 })204 );205206 it.effect("read a tree once per isolate, by its id", () =>207 Effect.gen(function* () {208 const reads = yield* Ref.make(0);209 const { fetch, first } = yield* platformWith(Option.some(reads));210 const path = `/${project}/raw/${first}/README.md`;211212 const once = yield* get(fetch, path);213 const counted = yield* Ref.get(reads);214 const again = yield* get(fetch, path);215216 expect([once.status, again.status, again.text]).toStrictEqual([217 200,218 200,219 readme,220 ]);221 expect(counted).toBeGreaterThan(0);222 expect(yield* Ref.get(reads)).toBe(counted);223 })224 );225226 it.effect("leave git's own paths to git", () =>227 Effect.gen(function* () {228 const { fetch } = yield* platform;229230 const answer = yield* get(231 fetch,232 `/${project}/info/refs?service=git-upload-pack`233 );234235 expect(answer.status).not.toBe(404);236 expect(answer.headers.get("content-security-policy")).toBeNull();237 })238 );239});
modified:apps/platform/test/w9-contracts.test.ts+15 added-17 removed
1/**2 * The code browser's, the people page's and drafting's contracts and3 * routes, wired end to end through the platform's fetch4 * handler before their bodies exist: the policy read answers, each code5 * read reaches the façade (which names the issue that builds it), a draft6 * needs a person, and `/` and a project's raw files have their slots, open7 * to a stale credential as every public path is.4 * handler: the policy read answers, the code reads reach the façade5 * (`why` names the issue that builds it; the others are6 * `code-reads.test.ts`'), a draft needs a person, and `/` and a project's7 * raw files have their routes, open to a stale credential as every public8 * path is (a raw file at no revision is a 404).9 */10import { describe, expect, it } from "@effect/vitest";10import { ProposalId } from "@repo/protocol/ids";11import { ProposalId, RepoPath } from "@repo/protocol/ids";12import { Unauthenticated } from "@repo/protocol/principal";13import { advanceTo } from "@repo/testkit/clock";14import { aProject, withAsk, withVouches } from "@repo/testkit/scenarios";15import { Cause, Effect, Exit, Layer, Option } from "effect";
54 unmodified lines
70 Effect.gen(function* () {71 const { handler } = yield* platform;72 const anyone = yield* rpcClient(handler);7373 expect(yield* diedWith(anyone.listRefs({ project }))).toStrictEqual(74 Option.some("not built: 903")75 );76 expect(yield* diedWith(anyone.readTree({ project }))).toStrictEqual(77 Option.some("not built: 903")78 );74 expect(75 yield* diedWith(76 anyone.why({ path: RepoPath.make("package.json"), project })77 )78 ).toStrictEqual(Option.some("not built: 912"));79 })80 );8182 it.effect("refuse a draft to anyone not signed in", () =>
49 unmodified lines
132 homeStale: {133 status: 501,134 text: "not built: 906 (draft model test-model)",135 },136 raw: { status: 501, text: "not built: 903" },137 rawStale: { status: 501, text: "not built: 903" },136 raw: { status: 404, text: "" },137 rawStale: { status: 404, text: "" },138 });139 })140 );141
4 unmodified lines
146 const response = yield* fetch(147 new Request(`${origin}/${project}/raw/info/refs`)148 );149150 expect(response.status).toBe(501);151 expect(yield* Effect.promise(() => response.text())).toBe(152 "not built: 903"153 );150 expect(response.status).toBe(404);151 expect(yield* Effect.promise(() => response.text())).toBe("");152 })153 );154});
modified:apps/web/src/dev/server.ts+51 added-13 removed
1/**2 * The dev world as a fetch handler: `POST /rpc` is an `RpcServer` over3 * `Contracts` with the dev handlers, protocol's `Authenticated` server side4 * over dev tokens (`sessions.ts`) and JSON, as the platform's `/rpc` serves5 * it, over a fresh world the seed has brought to its state. `backend.ts`6 * makes the one an isolate serves; a test makes its own.5 * it, over a fresh world the seed has brought to its state; and6 * `GET /<project>/raw/<rev>/<path…>` answers a project's raw files with7 * the response the platform's `raw.ts` gives (`@repo/project/code/raw`).8 * `backend.ts` makes the one an isolate serves; a test makes its own.9 */10import { RepoHost } from "@repo/artifacts/repo-host";11import { rawFor } from "@repo/project/code/raw";12import { Projects } from "@repo/project/projects";13import { Contracts } from "@repo/protocol/contracts";9import { Layer } from "effect";10import { HttpRouter } from "effect/http";14import { ProjectName } from "@repo/protocol/ids";15import { Context, Effect, Layer, Option, Schema } from "effect";16import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";17import { RpcSerialization, RpcServer } from "effect/rpc";1819import { devHandlers } from "./handlers.ts";20import { seedDev } from "./seed.ts";
4 unmodified lines
25const seededWorld = Layer.effectDiscard(seedDev).pipe(26 Layer.provideMerge(devWorld)27);2829const decodeProject = Schema.decodeUnknownOption(ProjectName);3031/** `/<project>/raw/<rev>/<path…>`: a project's raw files, as the platform serves them. */32const raw = Layer.unwrap(33 Effect.gen(function* () {34 const services = Context.make(RepoHost, yield* RepoHost).pipe(35 Context.add(Projects, yield* Projects)36 );3738 return HttpRouter.add(39 "GET",40 "/:project/raw/*",41 Effect.gen(function* () {42 const params = yield* HttpRouter.params;43 const request = yield* HttpServerRequest.HttpServerRequest;4445 return yield* Option.match(decodeProject(params.project), {46 onNone: () =>47 Effect.succeed(HttpServerResponse.empty({ status: 404 })),48 onSome: (project) =>49 rawFor(project, request.url).pipe(50 Effect.provide(services),51 Effect.map(HttpServerResponse.fromWeb)52 ),53 });54 })55 );56 })57);5859/**24 * The contracts at `/rpc` over a fresh, seeded world. `toWebHandler` builds60 * The contracts at `/rpc` and the raw files over a fresh, seeded world. `toWebHandler` builds61 * its layer as soon as it is called, so the world is made and seeded from62 * that moment, and a request that arrives before the seed is done waits for63 * it. `dispose` ends the world.64 */65export const devServer = () =>66 HttpRouter.toWebHandler(67 Layer.merge(31 RpcServer.layerHttp({32 group: Contracts,33 path: "/rpc",34 protocol: "http",35 }).pipe(36 Layer.provide([devHandlers, devSessions, RpcSerialization.layerJson]),37 Layer.provide(seededWorld)38 ),68 RpcServer.layerHttp({69 group: Contracts,70 path: "/rpc",71 protocol: "http",72 }).pipe(73 Layer.provide([devHandlers, devSessions, RpcSerialization.layerJson])74 ),75 raw76 ).pipe(Layer.provide(seededWorld)),77 { disableLogger: true }78 );
modified:apps/web/test/dev-backend.test.ts+48 added
234 unmodified lines
235 );236 })237 );238});239240/** Each of `paths` on a fresh world's own handler: its status, headers and body. */241const fetched = (paths: readonly string[]) =>242 Effect.scoped(243 Effect.gen(function* () {244 const { dispose, handler } = devServer();245246 yield* Effect.addFinalizer(() => Effect.promise(dispose));247248 return yield* Effect.forEach(paths, (path) =>249 Effect.gen(function* () {250 const response = yield* Effect.promise(() =>251 handler(new Request(`http://localhost${path}`))252 );253254 return {255 cache: response.headers.get("cache-control"),256 csp: response.headers.get("content-security-policy") ?? "",257 nosniff: response.headers.get("x-content-type-options"),258 status: response.status,259 text: yield* Effect.promise(() => response.text()),260 };261 })262 );263 })264 );265266describe("the dev world's raw files", seededWorlds, () => {267 it.live(268 "answer a project's file as the platform does, and a path that climbs out with a 404",269 () =>270 Effect.gen(function* () {271 const [manifest, climbed] = yield* fetched([272 "/datekit/raw/main/package.json",273 "/datekit/raw/main/..%2F..%2Fpackage.json",274 ]);275276 expect(manifest).toMatchObject({277 cache: "public, max-age=60",278 nosniff: "nosniff",279 status: 200,280 });281 expect(manifest?.csp).toContain("sandbox");282 expect(manifest?.text).toContain('"name": "datekit"');283 expect([climbed?.status, climbed?.text]).toStrictEqual([404, ""]);284 })285 );286});
modified:packages/artifacts/src/repo-host.ts+8 added-2 removed
24 unmodified lines
25);2627export type BranchName = typeof BranchName.Type;2829/** A full ref name: `refs/heads/main`, `refs/asked/landed`, `refs/notes/commits`. */29/**30 * A full ref name: `refs/heads/main`, `refs/asked/landed`, `refs/notes/commits`,31 * `refs/tags/@changesets/cli@2.27.1` (a scoped package's tag; `@` and `+`32 * are git's as well).33 */34export const RefName = Schema.String.pipe(35 Schema.check(32 Schema.isPattern(/^refs\/(?!.*\.\.)[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+$/u)36 Schema.isPattern(37 /^refs\/(?!.*\.\.)[A-Za-z0-9._@+-]+(?:\/[A-Za-z0-9._@+-]+)+$/u38 )39 ),40 Schema.brand("RefName")41);42
198 unmodified lines
modified:packages/project/src/code/cache.ts+153 added-6 removed
1 unmodified line
2 * The code reads' cache: what an object id names never changes, so a read3 * keyed by `<repo>:<kind>:<object id>` (a tree, a blob, a commit, a commit's4 * diff, a blame at a commit) is read once. A `Context.Reference` whose5 * default caches nothing, so every host composes before one is given; the6 * platform gives one held in a layer (no module-level state, principle 6).7 * `main` is never a key: it resolves through the project's record on every6 * platform gives one held in a layer (no module-level state, principle 6),7 * so it lives as long as the isolate. `main` and a tag are never a key:8 * each resolves through the project's record or the repo's tags on every9 * call.10 *11 * Entries come in two weights, each in a cache of its own, so a count of12 * entries bounds the memory they take: trees and commits are light (a few13 * KiB), while a file's text, a commit's path list or changes and a page of14 * the log are heavy (up to hundreds of KiB), and an isolate holds 128 MB.15 */10import { Context } from "effect";11import type { Effect } from "effect";16import {17 Cache,18 Context,19 Duration,20 Effect,21 Equal,22 Exit,23 Hash,24 Layer,25 Option,26 Ref,27} from "effect";2829/** How a read's value is kept. */30export interface Keeping<A> {31 /** Whether the value may weigh up to hundreds of KiB (a text, a list). */32 readonly heavy?: boolean;33 /** Whether this value may be kept at all; a larger one is read again. */34 readonly keep?: (value: A) => boolean;35}3637/** The code reads, each kept by its key once read. */38export interface CodeReads {15 /** `read`, or what it gave before for `key`. */39 /**40 * `read`, or what it gave before for `key`. A failure is never kept,41 * and neither is a value `keeping.keep` turns down (a large file's text).42 */43 readonly through: <A, E, R>(44 key: string,18 read: Effect.Effect<A, E, R>45 read: Effect.Effect<A, E, R>,46 keeping?: Keeping<A>47 ) => Effect.Effect<A, E, R>;48}4950export const CodeCache = Context.Reference<CodeReads>("project/CodeCache", {51 defaultValue: () => ({ through: (_key, read) => read }),52});5354/** What one read gave, when it succeeded, and whether it may be kept. */55interface Entry {56 readonly value: Option.Option<unknown>;57 readonly kept: boolean;58}5960/**61 * One read and the key it is kept by: two are the same entry when their62 * keys are, whatever their reads (each a closure of its own).63 */64class Keyed implements Equal.Equal {65 readonly key: string;66 readonly read: Effect.Effect<Entry>;6768 constructor(key: string, read: Effect.Effect<Entry>) {69 this.key = key;70 this.read = read;71 }7273 [Equal.symbol](that: Equal.Equal): boolean {74 return that instanceof Keyed && that.key === this.key;75 }7677 [Hash.symbol](): number {78 return Hash.string(this.key);79 }80}8182const always = () => true;8384/** How long an entry is kept: for good when its read succeeded and may be kept, else not at all. */85const lifeOf = (exit: Exit.Exit<Entry>) =>86 Exit.isSuccess(exit) && exit.value.kept ? Duration.infinity : Duration.zero;8788/** One cache of at most `capacity` reads. */89const cacheOf = (capacity: number) =>90 Cache.makeWith((key: Keyed) => key.read, {91 capacity,92 timeToLive: lifeOf,93 });9495/** `read` through `cache`, kept by `key` when `keep` allows. */96const throughCache =97 (cache: Cache.Cache<Keyed, Entry>) =>98 <A, E, R>(99 key: string,100 read: Effect.Effect<A, E, R>,101 keep: (value: A) => boolean102 ) =>103 Effect.gen(function* () {104 const context = yield* Effect.context<R>();105 const own = yield* Ref.make(Option.none<Exit.Exit<A, E>>());106107 const entry = yield* Cache.get(108 cache,109 new Keyed(110 key,111 Effect.exit(Effect.provideContext(read, context)).pipe(112 Effect.tap((exit) => Ref.set(own, Option.some(exit))),113 Effect.map((exit): Entry => ({114 kept: Exit.isSuccess(exit) && keep(exit.value),115 value: Exit.isSuccess(exit)116 ? Option.some(exit.value)117 : Option.none(),118 }))119 )120 )121 );122123 const ran = yield* Ref.get(own);124125 if (Option.isSome(ran)) {126 return yield* ran.value;127 }128129 if (Option.isNone(entry.value)) {130 return yield* read;131 }132133 // SAFETY: every key names one kind of read (`<repo>:<kind>:<id>`), so the134 // value kept under it is what a read typed as this one gave.135 // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- one cache holds every kind of read, so its values are typed `unknown`; see SAFETY.136 return entry.value.value as A;137 });138139/**140 * At most `capacity` light reads and `heavy` heavy ones, the least141 * recently used of each dropped first. Two calls with one key while the142 * first is under way share its read; a caller whose own read ran gets its143 * exit as it was, and one that waited on a read that failed reads for144 * itself.145 */146export const CodeCacheLive = (147 capacity: number,148 heavy = Math.max(1, Math.ceil(capacity / 50))149) =>150 Layer.effect(151 CodeCache,152 Effect.gen(function* () {153 const light = throughCache(yield* cacheOf(capacity));154 const weighty = throughCache(yield* cacheOf(heavy));155156 const reads: CodeReads = {157 through: <A, E, R>(158 key: string,159 read: Effect.Effect<A, E, R>,160 keeping: Keeping<A> = {}161 ) =>162 (keeping.heavy === true ? weighty : light)(163 key,164 read,165 keeping.keep ?? always166 ),167 };168169 return reads;170 })171 );
added:packages/project/src/code/commit.ts+236 added
1/**2 * One commit and what it changed against its first parent (a root commit3 * against the empty tree), through `treeDiff` (`@repo/git/tree-diff`): each4 * file's status, both blob ids, whether it is binary, and its old and new5 * text. At most 300 files and 2 MiB of text in all: past 300 files every6 * file is a path only, and once the text runs past 2 MiB the files after7 * it are; either way the diff says it is `truncated`. The list of changes8 * is kept by the commit's id; the landing is asked for on every call.9 */10import { RepoHost } from "@repo/artifacts/repo-host";11import type { RepoNotFound, TreeEntry } from "@repo/artifacts/repo-host";12import { treeDiff } from "@repo/git/tree-diff";13import type { Change } from "@repo/git/tree-diff";14import type { ChangedFile, CommitDiff } from "@repo/protocol/domain/code";15import { BlobSha, TreeSha } from "@repo/protocol/ids";16import type { CommitSha, RepoName } from "@repo/protocol/ids";17import { UnknownCommit } from "@repo/protocol/refusal";18import { Array, Effect, Option, Order } from "effect";1920import type { CodeProject } from "../code.ts";21import { CodeCache } from "./cache.ts";22import { contentsOf } from "./file.ts";23import type { Contents } from "./file.ts";24import { commitViews } from "./log.ts";25import { filesUnder, PATHS_CAP } from "./paths.ts";26import { commitAt } from "./revision.ts";27import { entriesOf, entryAt } from "./tree.ts";2829/** The most files a commit's diff carries text for. */30export const DIFF_FILES = 300;3132/** The most text a commit's diff carries in all: 2 MiB. */33export const DIFF_TEXT = 2 * 1024 * 1024;3435/** The longest list of changes the cache keeps. */36const KEPT_CHANGES = 1000;3738/** A change, and whether each side is a submodule (whose id names no blob here). */39interface Changed extends Change {40 readonly links: { readonly before: boolean; readonly after: boolean };41}4243const isLink = (entry: Option.Option<TreeEntry>) =>44 Option.exists(entry, ({ type }) => type === "commit");4546/** Every file under a root commit's tree, each added. */47const rootChanges = (repo: RepoName, tree: string) =>48 Effect.map(filesUnder(repo, tree, PATHS_CAP), ({ files }) =>49 files.map(({ entry, path }): Changed => ({50 after: BlobSha.make(entry.sha),51 links: { after: entry.type === "commit", before: false },52 path,53 status: "added",54 }))55 );5657/**58 * What changed from `base` to `head`, by `treeDiff` over this repo's trees59 * read through the cache (so the side lookups that follow read none again).60 */61const changesBetween = (repo: RepoName, base: string, head: string) =>62 Effect.gen(function* () {63 const host = yield* RepoHost;6465 const changes = yield* treeDiff(66 repo,67 TreeSha.make(base),68 TreeSha.make(head)69 ).pipe(70 Effect.provideService(71 RepoHost,72 RepoHost.of({73 ...host,74 readTree: (name, id) =>75 name === repo76 ? Effect.asSome(77 Effect.provideService(entriesOf(repo, id), RepoHost, host)78 )79 : host.readTree(name, id),80 })81 )82 );8384 return yield* Effect.forEach(85 changes,86 (change): Effect.Effect<Changed, RepoNotFound, RepoHost> =>87 Effect.map(88 Effect.all([89 entryAt(repo, base, change.path),90 entryAt(repo, head, change.path),91 ]),92 ([before, after]) => ({93 ...change,94 links: { after: isLink(after), before: isLink(before) },95 })96 ),97 { concurrency: 8 }98 );99 });100101const byPath = Order.mapInput(Order.String, (change: Changed) => change.path);102103/** A side's contents, unless it is a submodule or absent. */104const sideOf = (105 repo: RepoName,106 blob: BlobSha | undefined,107 link: boolean108): Effect.Effect<Option.Option<Contents>, RepoNotFound, RepoHost> =>109 blob === undefined || link ? Effect.succeedNone : contentsOf(repo, blob);110111/** A change as a path, its status and its blob ids, with no text. */112const pathOnly = ({ after, before, path, status }: Changed): ChangedFile => {113 const file = { binary: false, path, status };114115 if (before !== undefined && after !== undefined) {116 return { ...file, after, before };117 }118119 if (before !== undefined) {120 return { ...file, before };121 }122123 return after === undefined ? file : { ...file, after };124};125126/** Each change with its text while the budget lasts, and whether any went without. */127const withText = (repo: RepoName, changes: readonly Changed[]) =>128 Effect.gen(function* () {129 if (changes.length > DIFF_FILES) {130 return { files: changes.map(pathOnly), truncated: true };131 }132133 const files: ChangedFile[] = [];134 let budget = DIFF_TEXT;135 let truncated = false;136137 for (const change of changes) {138 if (truncated) {139 files.push(pathOnly(change));140 continue;141 }142143 const before = yield* sideOf(repo, change.before, change.links.before);144 const after = yield* sideOf(repo, change.after, change.links.after);145 const oldText = Option.flatMap(before, ({ text }) => text);146 const newText = Option.flatMap(after, ({ text }) => text);147148 const size =149 Option.getOrElse(150 Option.map(oldText, (text) => text.length),151 () => 0152 ) +153 Option.getOrElse(154 Option.map(newText, (text) => text.length),155 () => 0156 );157158 if (size > budget) {159 truncated = true;160 files.push(pathOnly(change));161 continue;162 }163164 budget -= size;165166 files.push({167 ...pathOnly(change),168 binary:169 Option.exists(before, ({ binary }) => binary) ||170 Option.exists(after, ({ binary }) => binary),171 ...Option.match(oldText, {172 onNone: () => ({}),173 onSome: (text) => ({ oldText: text }),174 }),175 ...Option.match(newText, {176 onNone: () => ({}),177 onSome: (text) => ({ newText: text }),178 }),179 });180 }181182 return { files, truncated };183 });184185/** One commit and the files it changed against its first parent. */186export const commitDiff = (187 project: CodeProject,188 sha: CommitSha189): Effect.Effect<CommitDiff, UnknownCommit, RepoHost> =>190 Effect.gen(function* () {191 const { repo } = project;192 const cache = yield* CodeCache;193194 const commit = yield* commitAt(repo, sha).pipe(195 Effect.orDie,196 Effect.flatMap(197 Option.match({198 onNone: () => Effect.fail(new UnknownCommit({ sha })),199 onSome: Effect.succeed,200 })201 )202 );203204 const parent = yield* Option.match(205 Option.fromUndefinedOr(commit.parents[0]),206 {207 onNone: () => Effect.succeedNone,208 onSome: (first) => commitAt(repo, first),209 }210 ).pipe(Effect.orDie);211212 const changes = yield* cache213 .through(214 `${repo}:changes:${sha}`,215 Option.match(parent, {216 onNone: () => rootChanges(repo, commit.tree),217 onSome: ({ tree }) => changesBetween(repo, tree, commit.tree),218 }),219 // A longer list is listed again, over trees the cache keeps.220 { heavy: true, keep: (all) => all.length <= KEPT_CHANGES }221 )222 .pipe(Effect.orDie);223224 const { files, truncated } = yield* withText(225 repo,226 Array.sort(changes, byPath)227 ).pipe(Effect.orDie);228229 const [view] = yield* commitViews(project, [commit]);230231 if (view === undefined) {232 return yield* Effect.die(`no view of ${sha}`);233 }234235 return { commit: view, files, truncated };236 });
added:packages/project/src/code/file.ts+156 added
1/**2 * One file's contents as a reader sees them: its size, whether it is3 * binary (a NUL in its first 8 KiB, git's own test and `tree-diff.ts`'s),4 * and its text up to 1 MiB; past that, or when Artifacts answers that the5 * blob is too large to hold (`MEMORY_LIMIT`), it is truncated with no text.6 * Kept by the blob's id, unless its text is large.7 */8import { ObjectId, RepoHost } from "@repo/artifacts/repo-host";9import type { RepoNotFound } from "@repo/artifacts/repo-host";10import type { FileView, Rev } from "@repo/protocol/domain/code";11import { BlobSha } from "@repo/protocol/ids";12import type { RepoName, RepoPath } from "@repo/protocol/ids";13import { UnknownPath } from "@repo/protocol/refusal";14import type { UnknownRevision } from "@repo/protocol/refusal";15import { Effect, Option, Schema } from "effect";1617import type { CodeProject } from "../code.ts";18import { CodeCache } from "./cache.ts";19import { commitAt, resolveRev } from "./revision.ts";20import { entryAt } from "./tree.ts";2122/** The most text a file's view carries: 1 MiB. */23export const TEXT_CAP = 1024 * 1024;2425// git's own test: a NUL among the first bytes means the blob is not text.26const SNIFF = 8192;2728/** The largest text a cache entry keeps; a larger one is read again. */29const KEPT_TEXT = 256 * 1024;3031/** Whether `bytes` read as binary: a NUL among the first 8 KiB. */32export const isBinary = (bytes: Uint8Array) =>33 bytes.subarray(0, SNIFF).includes(0);3435/** A file's contents: its text only when it is text and within the cap. */36export interface Contents {37 readonly size: number;38 readonly binary: boolean;39 readonly truncated: boolean;40 readonly text: Option.Option<string>;41}4243/** What Artifacts throws when a blob is too large for the Worker to hold. */44const MemoryLimit = Schema.Struct({ code: Schema.Literal("MEMORY_LIMIT") });4546const isMemoryLimit = Schema.is(MemoryLimit);4748/**49 * `read`, or `tooLarge` when Artifacts said the blob was too large to hold:50 * its binding throws that as a defect, which here is an answer.51 */52export const unlessTooLarge = <A, E, R>(53 read: Effect.Effect<A, E, R>,54 tooLarge: () => A55): Effect.Effect<A, E, R> =>56 Effect.catchDefect(read, (defect) =>57 isMemoryLimit(defect) ? Effect.succeed(tooLarge()) : Effect.die(defect)58 );5960/** `bytes` as a reader sees them. */61export const contentsOfBytes = (bytes: Uint8Array): Contents => {62 const binary = isBinary(bytes);63 const truncated = !binary && bytes.length > TEXT_CAP;6465 return {66 binary,67 size: bytes.length,68 text:69 binary || truncated70 ? Option.none()71 : Option.some(new TextDecoder().decode(bytes)),72 truncated,73 };74};7576/**77 * The blob `blob`'s contents, kept by its id; none when the repo has no78 * blob by it (a submodule's commit).79 */80export const contentsOf = (81 repo: RepoName,82 blob: BlobSha83): Effect.Effect<Option.Option<Contents>, RepoNotFound, RepoHost> =>84 Effect.gen(function* () {85 const cache = yield* CodeCache;8687 return yield* cache.through(88 `${repo}:text:${blob}`,89 unlessTooLarge(90 RepoHost.use((host) => host.readBlob(repo, ObjectId.make(blob))).pipe(91 Effect.map(Option.map(contentsOfBytes))92 ),93 () =>94 Option.some({95 binary: false,96 size: 0,97 text: Option.none(),98 truncated: true,99 })100 ),101 {102 heavy: true,103 keep: (contents) =>104 Option.match(contents, {105 onNone: () => false,106 onSome: ({ text }) =>107 Option.match(text, {108 onNone: () => true,109 onSome: (read) => read.length <= KEPT_TEXT,110 }),111 }),112 }113 );114 });115116/** One file at `at`: its text, or that it is binary or too large. */117export const fileView = (118 project: CodeProject,119 at: Option.Option<Rev>,120 path: RepoPath121): Effect.Effect<FileView, UnknownRevision | UnknownPath, RepoHost> =>122 Effect.gen(function* () {123 const commit = yield* resolveRev(project, at);124125 const { tree } = yield* commitAt(project.repo, commit).pipe(126 Effect.flatMap(Effect.fromOption),127 Effect.orDie128 );129130 const entry = yield* entryAt(project.repo, tree, path).pipe(Effect.orDie);131132 if (Option.isNone(entry) || entry.value.type !== "blob") {133 return yield* new UnknownPath({ commit, path });134 }135136 const sha = BlobSha.make(entry.value.sha);137138 const contents = yield* contentsOf(project.repo, sha).pipe(139 Effect.orDie,140 Effect.flatMap(Effect.fromOption),141 Effect.orDie142 );143144 return {145 at: commit,146 binary: contents.binary,147 path,148 sha,149 size: contents.size,150 truncated: contents.truncated,151 ...Option.match(contents.text, {152 onNone: () => ({}),153 onSome: (text) => ({ text }),154 }),155 };156 });
added:packages/project/src/code/log.ts+212 added
1/**2 * The first-parent log from a revision, a page at a time: each commit as a3 * reader sees it (subject, body, trailers, who and when), and `landing`4 * only where the project's record has one, so a trailer in an imported5 * commit never reads as a landing. With a path, only the commits whose6 * first-parent change touched it, scanning at most 200 commits a call;7 * `next` is where the scan stopped, so the next page resumes it.8 */9import { Revision, RepoHost } from "@repo/artifacts/repo-host";10import type {11 Commit,12 RepoNotFound,13 TreeEntry,14} from "@repo/artifacts/repo-host";15import { parseTrailers } from "@repo/git/trailers";16import type { CommitView, Rev } from "@repo/protocol/domain/code";17import type { LandingView } from "@repo/protocol/domain/landing";18import { TreeSha } from "@repo/protocol/ids";19import type { CommitSha, RepoName, RepoPath } from "@repo/protocol/ids";20import type { UnknownRevision } from "@repo/protocol/refusal";21import { DateTime, Effect, Equal, Option } from "effect";2223import type { CodeProject } from "../code.ts";24import { CodeCache } from "./cache.ts";25import { commitAt, resolveRev } from "./revision.ts";26import { entryAt } from "./tree.ts";2728/** The most commits one page holds. */29export const LOG_LIMIT = 100;3031/** The most first-parent commits a path's log scans in one call. */32export const PATH_SCAN = 200;3334/** A commit as a reader sees it, with its landing when it is one. */35export const commitView = (36 commit: Commit,37 landing: Option.Option<LandingView>38): CommitView => {39 const [subject = "", ...rest] = commit.message.split("\n");4041 return {42 author: {43 at: DateTime.fromEpochSeconds(commit.authoredAt),44 email: commit.author.email,45 name: commit.author.name,46 },47 body: rest.join("\n").replace(/^\n+/u, ""),48 committer: {49 at: DateTime.fromEpochSeconds(commit.committedAt),50 email: commit.committer.email,51 name: commit.committer.name,52 },53 parents: commit.parents,54 sha: commit.sha,55 subject,56 trailers: parseTrailers(commit.message).map(({ key, value }) => ({57 key,58 value,59 })),60 tree: TreeSha.make(commit.tree),61 ...Option.match(landing, {62 onNone: () => ({}),63 onSome: (found) => ({ landing: found }),64 }),65 };66};6768/** `commits` as a reader sees them, each landing from one batch of the project's record. */69export const commitViews = (70 project: CodeProject,71 commits: readonly Commit[]72): Effect.Effect<readonly CommitView[]> =>73 Effect.map(74 commits.length === 075 ? Effect.succeed([])76 : project.landings(commits.map(({ sha }) => sha)),77 (landings) => {78 const bySha = new Map<string, LandingView>(79 landings.map((landing) => [landing.sha, landing])80 );8182 return commits.map((commit) =>83 commitView(commit, Option.fromUndefinedOr(bySha.get(commit.sha)))84 );85 }86 );8788/**89 * `count` first-parent commits from `sha`, the first `from` skipped: a90 * commit's history never changes, so the page is kept by its start.91 */92const pageOf = (93 repo: RepoName,94 sha: CommitSha,95 from: number,96 count: number97): Effect.Effect<readonly Commit[], RepoNotFound, RepoHost> =>98 Effect.gen(function* () {99 const cache = yield* CodeCache;100101 return yield* cache.through(102 `${repo}:log:${sha}:${from}:${count}`,103 RepoHost.use((host) =>104 host.log(repo, Revision.Commit({ sha }), count, from)105 ),106 { heavy: true }107 );108 });109110/** What sits at `path` in `tree`: its id and mode, or nothing. */111const idAt = (repo: RepoName, tree: string, path: RepoPath) =>112 Effect.map(113 entryAt(repo, tree, path),114 Option.map(({ mode, sha }: TreeEntry) => `${mode} ${sha}`)115 );116117/** A page of the log, and where the next starts when there is more. */118export interface LogPage {119 readonly commits: readonly CommitView[];120 readonly next?: number;121}122123const pageWith = (124 commits: readonly CommitView[],125 next: Option.Option<number>126): LogPage =>127 Option.match(next, {128 onNone: () => ({ commits }),129 onSome: (at) => ({ commits, next: at }),130 });131132/** A page of first-parent commits from `at`, each landing with its record. */133export const logPage = (134 project: CodeProject,135 input: {136 readonly at: Option.Option<Rev>;137 readonly path: Option.Option<RepoPath>;138 readonly from: number;139 readonly limit: number;140 }141): Effect.Effect<LogPage, UnknownRevision, RepoHost> =>142 Effect.gen(function* () {143 const sha = yield* resolveRev(project, input.at);144 const from = Math.max(0, Math.floor(input.from));145 const limit = Math.min(LOG_LIMIT, Math.max(1, Math.floor(input.limit)));146 const { repo } = project;147148 if (Option.isNone(input.path)) {149 const read = yield* pageOf(repo, sha, from, limit + 1).pipe(Effect.orDie);150 const commits = yield* commitViews(project, read.slice(0, limit));151152 return pageWith(153 commits,154 read.length > limit ? Option.some(from + limit) : Option.none()155 );156 }157158 const path = input.path.value;159160 // One past the scan, so the last scanned commit's parent is at hand161 // and whether history goes on is known.162 const scan = yield* pageOf(repo, sha, from, PATH_SCAN + 1).pipe(163 Effect.orDie164 );165166 const scanned = scan.slice(0, PATH_SCAN);167 const touched: Commit[] = [];168169 for (const [at, commit] of scanned.entries()) {170 const parent = Option.fromUndefinedOr(commit.parents[0]);171 const after = Option.fromUndefinedOr(scan[at + 1]);172173 // The log is first parents, so the next commit in it is this one's174 // parent; only past the scan is the parent read on its own.175 const parentCommit = yield* Option.match(parent, {176 onNone: () => Effect.succeedNone,177 onSome: (first) =>178 Option.exists(after, ({ sha: next }) => next === first)179 ? Effect.succeed(after)180 : commitAt(repo, first),181 }).pipe(Effect.orDie);182183 const parentTree = Option.map(parentCommit, ({ tree }) => tree);184185 const now = yield* idAt(repo, commit.tree, path).pipe(Effect.orDie);186187 const before = yield* Option.match(parentTree, {188 onNone: () => Effect.succeedNone,189 onSome: (tree) => idAt(repo, tree, path),190 }).pipe(Effect.orDie);191192 if (!Equal.equals(now, before)) {193 touched.push(commit);194 }195196 if (touched.length === limit) {197 const commits = yield* commitViews(project, touched);198199 return pageWith(200 commits,201 at + 1 < scan.length ? Option.some(from + at + 1) : Option.none()202 );203 }204 }205206 const commits = yield* commitViews(project, touched);207208 return pageWith(209 commits,210 scan.length > PATH_SCAN ? Option.some(from + PATH_SCAN) : Option.none()211 );212 });
added:packages/project/src/code/paths.ts+125 added
1/**2 * Every file of a commit: each blob, symlink and submodule path under its3 * root tree, up to 50,000 (a file tree's sidebar), kept by the root tree's4 * id. The walk reads at most eight trees at once, one depth at a time, and5 * stops descending once the cap is passed.6 */7import type {8 RepoHost,9 RepoNotFound,10 TreeEntry,11} from "@repo/artifacts/repo-host";12import type { PathList, Rev } from "@repo/protocol/domain/code";13import { RepoPath } from "@repo/protocol/ids";14import type { RepoName } from "@repo/protocol/ids";15import type { UnknownRevision } from "@repo/protocol/refusal";16import type { Option } from "effect";17import { Array, Effect, Order } from "effect";1819import type { CodeProject } from "../code.ts";20import { CodeCache } from "./cache.ts";21import { commitAt, resolveRev } from "./revision.ts";22import { entriesOf } from "./tree.ts";2324/** The most paths a commit's list holds. */25export const PATHS_CAP = 50_000;2627/** The longest path list the cache keeps: about 1 MB of paths. */28const KEPT_PATHS = 10_000;2930// Store calls under way at once, however wide or deep the tree.31const STORE_CALLS = 8;3233/** One file under a root tree, with the entry that names it. */34export interface FileAt {35 readonly path: RepoPath;36 readonly entry: TreeEntry;37}3839/** A folder still to read: its path's prefix and its tree's id. */40interface Folder {41 readonly prefix: string;42 readonly tree: string;43}4445/**46 * Every file under the tree `root`, in path order; past `cap`, the walk47 * stops and says so. It reads one depth at a time, so which folders it48 * reaches before it stops depends on the tree alone, never on which read49 * came back first: the same tree gives the same list (principle 8).50 */51export const filesUnder = (52 repo: RepoName,53 root: string,54 cap: number55): Effect.Effect<56 { readonly files: readonly FileAt[]; readonly truncated: boolean },57 RepoNotFound,58 RepoHost59> =>60 Effect.gen(function* () {61 const found: FileAt[] = [];62 let depth: readonly Folder[] = [{ prefix: "", tree: root }];6364 while (depth.length > 0 && found.length <= cap) {65 const read = yield* Effect.forEach(66 depth,67 ({ prefix, tree }) =>68 Effect.map(entriesOf(repo, tree), (entries) => ({ entries, prefix })),69 { concurrency: STORE_CALLS }70 );7172 const deeper: Folder[] = [];7374 for (const { entries, prefix } of read) {75 for (const entry of entries) {76 if (entry.type === "tree") {77 deeper.push({ prefix: `${prefix}${entry.name}/`, tree: entry.sha });78 } else {79 found.push({80 entry,81 path: RepoPath.make(`${prefix}${entry.name}`),82 });83 }84 }85 }8687 depth = deeper;88 }8990 const all = Array.sort(91 found,92 Order.mapInput(Order.String, (file: FileAt) => file.path)93 );9495 return {96 files: all.slice(0, cap),97 truncated: all.length > cap || depth.length > 0,98 };99 });100101/** Every file path at `at`, up to the cap. */102export const pathList = (103 project: CodeProject,104 at: Option.Option<Rev>105): Effect.Effect<PathList, UnknownRevision, RepoHost> =>106 Effect.gen(function* () {107 const commit = yield* resolveRev(project, at);108 const cache = yield* CodeCache;109110 const { tree } = yield* commitAt(project.repo, commit).pipe(111 Effect.flatMap(Effect.fromOption),112 Effect.orDie113 );114115 const { files, truncated } = yield* cache116 .through(117 `${project.repo}:paths:${tree}`,118 filesUnder(project.repo, tree, PATHS_CAP),119 // A longer list is walked again, over trees the cache keeps.120 { heavy: true, keep: (list) => list.files.length <= KEPT_PATHS }121 )122 .pipe(Effect.orDie);123124 return { at: commit, paths: files.map(({ path }) => path), truncated };125 });
added:packages/project/src/code/raw.ts+194 added
1/**2 * A project's raw bytes, `GET /<project>/raw/<rev>/<path…>` (spec W9-D6),3 * as one pure response both the platform (`apps/platform/src/raw.ts`) and4 * the web's dev world serve. Both origins hold a session cookie, so no file5 * may run as script there: every answer carries `nosniff` and a sandboxing6 * CSP, images come back as themselves (an SVG too: an `<img>` never runs7 * its script, and opened on its own the sandbox gives it no script and an8 * opaque origin), markup and every other text as plain text, and anything9 * else binary as bytes to save. A file at a commit's id never changes, so10 * it is cached for good; at a name that moves, for a minute. Anything that11 * is not a file at a revision is a 404 that says nothing of the repo.12 */13import { ObjectId, RepoHost } from "@repo/artifacts/repo-host";14import { Rev } from "@repo/protocol/domain/code";15import { BlobSha, RepoPath } from "@repo/protocol/ids";16import type { ProjectName } from "@repo/protocol/ids";17import { Effect, Option, Schema } from "effect";1819import { codeProjectOf } from "../code.ts";20import type { CodeProject } from "../code.ts";21import { Projects } from "../projects.ts";22import { isBinary, unlessTooLarge } from "./file.ts";23import { commitAt, isFullSha, resolveRev } from "./revision.ts";24import { entryAt, segmentsOf } from "./tree.ts";2526/** What a raw answer may load and do: nothing but its own images and inline styles, sandboxed. */27const SANDBOX =28 "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; sandbox";2930const IMAGES = new Map([31 ["avif", "image/avif"],32 ["gif", "image/gif"],33 ["ico", "image/x-icon"],34 ["jpeg", "image/jpeg"],35 ["jpg", "image/jpeg"],36 ["png", "image/png"],37 ["svg", "image/svg+xml"],38 ["webp", "image/webp"],39]);4041const TEXT = "text/plain; charset=utf-8";4243/** What every raw answer carries, a refusal too (spec W9-D6). */44const SAFE = {45 "content-security-policy": SANDBOX,46 "x-content-type-options": "nosniff",47} as const;4849/** `path`'s extension, lowercased; none without one. */50const extensionOf = (path: string) => {51 const name = path.slice(path.lastIndexOf("/") + 1);52 const dot = name.lastIndexOf(".");5354 return dot <= 0 ? "" : name.slice(dot + 1).toLowerCase();55};5657/**58 * The headers a raw answer for the blob `blob` at `path` carries: its type59 * by extension (an image as itself, anything else as plain text, or as60 * bytes when `binary`), `nosniff` and the sandbox, and a cache for good61 * when `rev` is a commit's id, for a minute when it is a name.62 */63export const rawHeaders = (64 path: RepoPath,65 rev: "sha" | "ref",66 blob: BlobSha,67 binary = false68): Headers => {69 const headers = new Headers({70 ...SAFE,71 "content-type":72 IMAGES.get(extensionOf(path)) ??73 (binary ? "application/octet-stream" : TEXT),74 });7576 if (rev === "sha") {77 headers.set("cache-control", "public, max-age=31536000, immutable");78 headers.set("etag", `"${blob}"`);79 } else {80 headers.set("cache-control", "public, max-age=60");81 }8283 return headers;84};8586/** A 404 that says nothing of the repo. */87const notFound = () => new Response(null, { headers: SAFE, status: 404 });8889/** A 413: Artifacts said the blob is too large to hold. */90const tooLarge = () => new Response(null, { headers: SAFE, status: 413 });9192/** The file `path` at `rev` of the project's canonical repo, as raw bytes. */93export const rawOf = (94 project: CodeProject,95 rev: Rev,96 path: RepoPath97): Effect.Effect<Response, never, RepoHost> =>98 Effect.gen(function* () {99 const commit = yield* resolveRev(project, Option.some(rev));100101 const { tree } = yield* commitAt(project.repo, commit).pipe(102 Effect.flatMap(Effect.fromOption)103 );104105 const entry = yield* entryAt(project.repo, tree, path);106107 if (Option.isNone(entry) || entry.value.type !== "blob") {108 return notFound();109 }110111 const blob = BlobSha.make(entry.value.sha);112113 const bytes = yield* RepoHost.use((host) =>114 host.readBlob(project.repo, ObjectId.make(blob))115 );116117 return Option.match(bytes, {118 onNone: notFound,119 onSome: (read) =>120 new Response(new Uint8Array(read), {121 headers: rawHeaders(122 path,123 isFullSha(rev) ? "sha" : "ref",124 blob,125 isBinary(read)126 ),127 status: 200,128 }),129 });130 }).pipe(131 (read) => unlessTooLarge(read, tooLarge),132 Effect.catchTags({133 NoSuchElementError: () => Effect.succeed(notFound()),134 RepoNotFound: () => Effect.succeed(notFound()),135 UnknownRevision: () => Effect.succeed(notFound()),136 })137 );138139const decodeRev = Schema.decodeUnknownOption(Rev);140141const decodePath = Schema.decodeUnknownOption(RepoPath);142143const decoded = Option.liftThrowable(decodeURIComponent);144145/**146 * A raw request's revision and path from everything after `raw/`, as the147 * URL carries it: the first segment is the revision (a tag's `/` arrives148 * as `%2F`), the rest the file's path, each decoded once. A path with an149 * empty, `.` or `..` segment, before or after decoding, is none.150 */151export const rawRequestOf = (152 rest: string153): Option.Option<{ readonly rev: Rev; readonly path: RepoPath }> => {154 const slash = rest.indexOf("/");155156 if (slash === -1) {157 return Option.none();158 }159160 return Option.all({161 path: decoded(rest.slice(slash + 1)).pipe(162 Option.filter((path) => Option.isSome(segmentsOf(path))),163 Option.flatMap(decodePath)164 ),165 rev: Option.flatMap(decoded(rest.slice(0, slash)), decodeRev),166 });167};168169/**170 * Everything after `/<project>/raw/` in a request's URL (whole, or its path171 * and query), still encoded. Read from the URL itself, not a router's172 * parameter: a router decodes `%2F`, which would cut a tag's name173 * (`%40datekit%2Fcore%402.0.0`) in two.174 */175export const rawRestOf = (url: string): string =>176 new URL(url, "http://raw.invalid").pathname.split("/").slice(3).join("/");177178/**179 * The answer to `GET /<project>/raw/<rest>` at `url` (whole, or its path180 * and query): the project found by its name, then its file. A project181 * never made is a 404 too.182 */183export const rawFor = (184 project: ProjectName,185 url: string186): Effect.Effect<Response, never, RepoHost | Projects> =>187 Option.match(rawRequestOf(rawRestOf(url)), {188 onNone: () => Effect.succeed(notFound()),189 onSome: ({ path, rev }) =>190 Projects.use((projects) => projects.get(project)).pipe(191 Effect.flatMap((api) => rawOf(codeProjectOf(api, project), rev, path)),192 Effect.catchTag("UnknownProject", () => Effect.succeed(notFound()))193 ),194 });
added:packages/project/src/code/refs.ts+112 added
1/**2 * A project's refs as readers see them: main's landed commit (the3 * project's record, never a ref), its tags peeled to their commits (the4 * repo's `tags`) and sorted by version, newest first, and its forks. Only5 * `refs/tags/*` is read: nothing of the platform's own (its landed mirror,6 * compose refs, notes) and no branch but main ever shows.7 */8import { RepoHost } from "@repo/artifacts/repo-host";9import { TagName } from "@repo/protocol/domain/code";10import type { RefsView, TagRef } from "@repo/protocol/domain/code";11import { Array, Effect, Option, Schema } from "effect";1213import type { CodeProject } from "../code.ts";14import { tagNameOf } from "./revision.ts";1516/** A name cut into runs of digits and runs of anything else. */17const runsOf = (name: string) => name.match(/\d+|\D+/gu) ?? [];1819const isDigits = (run: string) => /^\d/u.test(run);2021/** Two strings as written, code point by code point. */22const compareText = (one: string, other: string) => {23 if (one === other) {24 return 0;25 }2627 return one < other ? -1 : 1;28};2930/** Two runs of digits by their value, however long. */31const compareNumbers = (one: string, other: string) => {32 const left = one.replace(/^0+(?=\d)/u, "");33 const right = other.replace(/^0+(?=\d)/u, "");3435 if (left.length !== right.length) {36 return left.length < right.length ? -1 : 1;37 }3839 return compareText(left, right);40};4142/**43 * Tags newest first, by version: runs of digits compare by value, so44 * `v1.10.0` comes before `v1.9.0`, and a release before its own45 * pre-releases (`v1.10.0` before `v1.10.0-beta.1`). Names are otherwise46 * compared as written, so a scoped package's tags stay together.47 */48export const compareTags = (one: string, other: string): number => {49 const left = runsOf(one);50 const right = runsOf(other);5152 for (let at = 0; at < Math.min(left.length, right.length); at += 1) {53 const mine = left[at] ?? "";54 const theirs = right[at] ?? "";5556 const order =57 isDigits(mine) && isDigits(theirs)58 ? compareNumbers(mine, theirs)59 : compareText(mine, theirs);6061 if (order !== 0) {62 return -order;63 }64 }6566 if (left.length === right.length) {67 return 0;68 }6970 // One name runs on past the other: a pre-release (`-beta.1`) is older71 // than its release, anything else newer.72 const longer = left.length > right.length ? left : right;73 const rest = longer[Math.min(left.length, right.length)] ?? "";74 const longerIsNewer = !rest.startsWith("-");75 const leftIsLonger = left.length > right.length;7677 return leftIsLonger === longerIsNewer ? -1 : 1;78};7980const decodeTag = Schema.decodeUnknownOption(TagName);8182/** Main's landed commit, its tags peeled and sorted newest first, and its forks. */83export const refsView = (84 project: CodeProject85): Effect.Effect<RefsView, never, RepoHost> =>86 Effect.gen(function* () {87 const landed = yield* project.head;88 const forks = yield* project.forks;8990 const tags = yield* RepoHost.use((host) => host.tags(project.repo)).pipe(91 Effect.catchTag("RepoNotFound", () => Effect.succeed([]))92 );9394 const named = Array.getSomes(95 tags.map(({ name, sha }) =>96 Option.map(97 Option.flatMap(tagNameOf(name), decodeTag),98 (tag): TagRef => ({ name: tag, sha })99 )100 )101 );102103 return {104 forks,105 project: project.project,106 tags: named.toSorted((one, other) => compareTags(one.name, other.name)),107 ...Option.match(landed, {108 onNone: () => ({}),109 onSome: (sha) => ({ landed: sha }),110 }),111 };112 });
added:packages/project/src/code/revision.ts+99 added
1/**2 * A revision as a reader names it, resolved to the commit it means in the3 * project's canonical repo (spec W9-D3): absent or `main` is main's landed4 * commit, from the project's record and never from a ref; 40 hex digits are5 * that commit, if the repo holds it; anything else is a tag's exact name,6 * found among the repo's tags and never joined into a ref path, so7 * `../heads/x` or a ref of the platform's own names nothing.8 */9import { RepoHost } from "@repo/artifacts/repo-host";10import type { Commit, RepoNotFound } from "@repo/artifacts/repo-host";11import type { Rev } from "@repo/protocol/domain/code";12import { CommitSha } from "@repo/protocol/ids";13import type { RepoName } from "@repo/protocol/ids";14import { UnknownRevision } from "@repo/protocol/refusal";15import { Array, Effect, Option } from "effect";1617import type { CodeProject } from "../code.ts";18import { CodeCache } from "./cache.ts";1920/** A full commit id: 40 lowercase hex digits. Short ids are not resolved. */21const FULL_SHA = /^[0-9a-f]{40}$/u;2223/** Whether `rev` names a commit by its full id (and so never moves). */24export const isFullSha = (rev: string) => FULL_SHA.test(rev);2526/** Where every tag's name starts. */27const TAGS = "refs/tags/";2829/** A ref name's tag name, when it is a tag's. */30export const tagNameOf = (ref: string): Option.Option<string> =>31 ref.startsWith(TAGS) ? Option.some(ref.slice(TAGS.length)) : Option.none();3233/**34 * The commit `sha` in `repo`, kept once found. A miss is not kept: the35 * commit may yet be pushed.36 */37export const commitAt = (38 repo: RepoName,39 sha: CommitSha40): Effect.Effect<Option.Option<Commit>, RepoNotFound, RepoHost> =>41 Effect.gen(function* () {42 const cache = yield* CodeCache;4344 return yield* cache45 .through(46 `${repo}:commit:${sha}`,47 RepoHost.use((host) => host.readCommit(repo, sha)).pipe(48 Effect.flatMap(Effect.fromOption)49 )50 )51 .pipe(52 Effect.asSome,53 Effect.catchTag("NoSuchElementError", () => Effect.succeedNone)54 );55 });5657/** The commit `at` names in the project's canonical repo. */58export const resolveRev = (59 project: CodeProject,60 at: Option.Option<Rev>61): Effect.Effect<CommitSha, UnknownRevision, RepoHost> => {62 const rev = Option.getOrElse(at, () => "main");63 const unknown = new UnknownRevision({ rev });6465 if (rev === "main") {66 return Effect.flatMap(project.head, (landed) =>67 Option.match(landed, {68 onNone: () => Effect.fail(unknown),69 onSome: (sha) => Effect.succeed<CommitSha>(sha),70 })71 );72 }7374 if (isFullSha(rev)) {75 const sha = CommitSha.make(rev);7677 return commitAt(project.repo, sha).pipe(78 Effect.catchTag("RepoNotFound", () => Effect.succeedNone),79 Effect.flatMap((found) =>80 Option.isSome(found) ? Effect.succeed(sha) : Effect.fail(unknown)81 )82 );83 }8485 return RepoHost.use((host) => host.tags(project.repo)).pipe(86 Effect.catchTag("RepoNotFound", () => Effect.succeed([])),87 Effect.flatMap((tags) =>88 Option.match(89 Array.findFirst(tags, ({ name }) =>90 Option.contains(tagNameOf(name), rev)91 ),92 {93 onNone: () => Effect.fail(unknown),94 onSome: ({ sha }) => Effect.succeed(sha),95 }96 )97 )98 );99};
added:packages/project/src/code/tree.ts+185 added
1/**2 * Folders of a commit: a tree's entries by its id (kept once read), the3 * entry at a path, walked one segment at a time, and one folder as a4 * reader lists it: folders first, then by name, each entry by its kind,5 * with its README by GitLab's precedence, any case.6 */7import { ObjectId, RepoHost } from "@repo/artifacts/repo-host";8import type { RepoNotFound, TreeEntry } from "@repo/artifacts/repo-host";9import type { CodeEntry, Rev, TreeListing } from "@repo/protocol/domain/code";10import { BlobSha, RepoPath } from "@repo/protocol/ids";11import type { CommitSha, RepoName } from "@repo/protocol/ids";12import { UnknownPath } from "@repo/protocol/refusal";13import type { UnknownRevision } from "@repo/protocol/refusal";14import { Array, Effect, Match, Option, Order } from "effect";1516import type { CodeProject } from "../code.ts";17import { CodeCache } from "./cache.ts";18import { commitAt, resolveRev } from "./revision.ts";1920/** The entries of the tree `id`; a tree a commit or a tree names is always there. */21export const entriesOf = (22 repo: RepoName,23 id: string24): Effect.Effect<readonly TreeEntry[], RepoNotFound, RepoHost> =>25 Effect.gen(function* () {26 const cache = yield* CodeCache;2728 return yield* cache.through(29 `${repo}:tree:${id}`,30 RepoHost.use((host) => host.readTree(repo, ObjectId.make(id))).pipe(31 Effect.flatMap(32 Option.match({33 onNone: () => Effect.die(`${repo} has no tree ${id}`),34 onSome: Effect.succeed,35 })36 )37 )38 );39 });4041/** The segments of `path`; none when one is empty, `.` or `..`. */42export const segmentsOf = (path: string): Option.Option<readonly string[]> => {43 const segments = path.split("/");4445 return segments.every(46 (segment) => segment !== "" && segment !== "." && segment !== ".."47 )48 ? Option.some(segments)49 : Option.none();50};5152/** The entry at `path` under the tree `root`, walked one segment at a time. */53export const entryAt = (54 repo: RepoName,55 root: string,56 path: string57): Effect.Effect<Option.Option<TreeEntry>, RepoNotFound, RepoHost> =>58 Option.match(segmentsOf(path), {59 onNone: () => Effect.succeedNone,60 onSome: (segments) =>61 Effect.gen(function* () {62 let tree = root;63 let found: Option.Option<TreeEntry> = Option.none();6465 for (const [at, segment] of segments.entries()) {66 if (at > 0) {67 if (Option.isNone(found) || found.value.type !== "tree") {68 return Option.none();69 }7071 tree = found.value.sha;72 }7374 const entries = yield* entriesOf(repo, tree);7576 found = Array.findFirst(entries, ({ name }) => name === segment);77 }7879 return found;80 }),81 });8283/** What a reader sees an entry as: a gitlink is a submodule, mode 120000 a symlink. */84export const kindOf = (entry: TreeEntry): CodeEntry["type"] =>85 Match.value(entry).pipe(86 Match.when({ type: "tree" }, () => "tree" as const),87 Match.when({ type: "commit" }, () => "submodule" as const),88 Match.when({ mode: "120000" }, () => "symlink" as const),89 Match.orElse(() => "blob" as const)90 );9192/** Folders first, then by name. */93const byKindThenName = Order.combine(94 Order.mapInput(Order.Boolean, (entry: CodeEntry) => entry.type !== "tree"),95 Order.mapInput(Order.String, (entry: CodeEntry) => entry.name)96);9798/** GitLab's README precedence, lowercased. */99const README = [100 "readme.md",101 "readme.markdown",102 "readme.mdown",103 "readme",104 "readme.txt",105 "readme.rst",106];107108const readmeOf = (entries: readonly CodeEntry[]) =>109 Array.findFirst(README, (name) =>110 Array.findFirst(111 entries,112 (entry) => entry.type === "blob" && entry.name.toLowerCase() === name113 )114 ).pipe(Option.map(({ path, sha }) => ({ path, sha: BlobSha.make(sha) })));115116/** The tree `path` names at `commit`, or `UnknownPath`. */117export const folderAt = (118 repo: RepoName,119 commit: CommitSha,120 path: Option.Option<RepoPath>121): Effect.Effect<string, UnknownPath, RepoHost> =>122 Effect.gen(function* () {123 const found = yield* commitAt(repo, commit).pipe(124 Effect.flatMap(Effect.fromOption)125 );126127 if (Option.isNone(path)) {128 return found.tree;129 }130131 const entry = yield* entryAt(repo, found.tree, path.value);132133 if (Option.isNone(entry) || entry.value.type !== "tree") {134 return yield* new UnknownPath({ commit, path: path.value });135 }136137 return entry.value.sha;138 }).pipe(139 Effect.catchTags({140 NoSuchElementError: Effect.die,141 RepoNotFound: Effect.die,142 })143 );144145/** One folder at `at`, folders first, with its README. */146export const listing = (147 project: CodeProject,148 at: Option.Option<Rev>,149 path: Option.Option<RepoPath>150): Effect.Effect<TreeListing, UnknownRevision | UnknownPath, RepoHost> =>151 Effect.gen(function* () {152 const commit = yield* resolveRev(project, at);153 const tree = yield* folderAt(project.repo, commit, path);154155 const prefix = Option.match(path, {156 onNone: () => "",157 onSome: (folder) => `${folder}/`,158 });159160 const read = yield* entriesOf(project.repo, tree).pipe(Effect.orDie);161162 const entries = Array.sort(163 read.map((entry): CodeEntry => ({164 mode: entry.mode,165 name: entry.name,166 path: RepoPath.make(`${prefix}${entry.name}`),167 sha: entry.sha,168 type: kindOf(entry),169 })),170 byKindThenName171 );172173 return {174 at: commit,175 entries,176 ...Option.match(path, {177 onNone: () => ({}),178 onSome: (folder) => ({ path: folder }),179 }),180 ...Option.match(readmeOf(entries), {181 onNone: () => ({}),182 onSome: (readme) => ({ readme }),183 }),184 };185 });
modified:packages/project/src/code.ts+31 added-21 removed
5 unmodified lines
6 * the web's dev world call these with the `RepoHost` they run on, and7 * consult the project's record only for main's landed commit, its landings8 * and its forks (`CodeProject`). Reads by object id go through `CodeCache`.9 *10 * Stubs until 903 (every read but `whyOf`) and 912 (`whyOf`) land; the11 * signatures are final.10 * Each read lives in its own module under `code/`; `whyOf` is a stub until11 * 912 lands.12 */13import type { RepoHost } from "@repo/artifacts/repo-host";14import type {15 CommitDiff,
20 unmodified lines
36 UnknownRevision,37} from "@repo/protocol/refusal";38import { Effect, Option } from "effect";3940import { commitDiff } from "./code/commit.ts";41import { fileView } from "./code/file.ts";42import { logPage } from "./code/log.ts";43import { pathList } from "./code/paths.ts";44import { refsView } from "./code/refs.ts";45import { listing } from "./code/tree.ts";46import type { ProjectApi } from "./project.ts";4748/** What the code reads take from a project's record, beside its canonical repo. */49export interface CodeProject {50 /** The project, as its refs name it. */51 readonly project: ProjectName;52 /** The project's canonical repo: never a fork's or a layer's. */53 readonly repo: RepoName;54 /** Main's landed commit; none before the first push. */55 readonly head: Effect.Effect<Option.Option<LandedSha>>;
11 unmodified lines
67): CodeProject => ({68 forks: api.forks(),69 head: Effect.map(api.head(), ({ landed }) => Option.fromUndefinedOr(landed)),70 landings: api.landings,71 project,72 repo: RepoName.make(project),73});7475const notBuilt = (issue: string) => Effect.die(`not built: ${issue}`);7677/** Main's landed commit, its tags peeled and sorted newest first, and its forks. */78export const refsOf = (70 _project: CodeProject71): Effect.Effect<RefsView, never, RepoHost> => notBuilt("903");79 project: CodeProject80): Effect.Effect<RefsView, never, RepoHost> => refsView(project);8182/** One folder at `at` (main when none), folders first, with its README. */83export const treeOf = (75 _project: CodeProject,76 _at: Option.Option<Rev>,77 _path: Option.Option<RepoPath>84 project: CodeProject,85 at: Option.Option<Rev>,86 path: Option.Option<RepoPath>87): Effect.Effect<TreeListing, UnknownRevision | UnknownPath, RepoHost> =>79 notBuilt("903");88 listing(project, at, path);8990/** Every file path at `at`, up to the cap. */91export const pathsOf = (83 _project: CodeProject,84 _at: Option.Option<Rev>85): Effect.Effect<PathList, UnknownRevision, RepoHost> => notBuilt("903");92 project: CodeProject,93 at: Option.Option<Rev>94): Effect.Effect<PathList, UnknownRevision, RepoHost> => pathList(project, at);9596/** One file at `at`: its text, or that it is binary or too large. */97export const fileOf = (89 _project: CodeProject,90 _at: Option.Option<Rev>,91 _path: RepoPath98 project: CodeProject,99 at: Option.Option<Rev>,100 path: RepoPath101): Effect.Effect<FileView, UnknownRevision | UnknownPath, RepoHost> =>93 notBuilt("903");102 fileView(project, at, path);103104/** A page of first-parent commits from `at`, each landing with its record. */105export const logOf = (97 _project: CodeProject,98 _input: {106 project: CodeProject,107 input: {108 readonly at: Option.Option<Rev>;109 readonly path: Option.Option<RepoPath>;110 readonly from: number;111 readonly limit: number;
1 unmodified line
113): Effect.Effect<114 { readonly commits: readonly CommitView[]; readonly next?: number },115 UnknownRevision,116 RepoHost108> => notBuilt("903");117> => logPage(project, input);118119/** One commit and the files it changed against its first parent. */120export const commitOf = (112 _project: CodeProject,113 _sha: CommitSha114): Effect.Effect<CommitDiff, UnknownCommit, RepoHost> => notBuilt("903");121 project: CodeProject,122 sha: CommitSha123): Effect.Effect<CommitDiff, UnknownCommit, RepoHost> =>124 commitDiff(project, sha);125126/** Why each line of a file at `at` is there. */127export const whyOf = (128 _project: CodeProject,
4 unmodified lines
modified:packages/project/test/code-facade.test.ts+7 added-36 removed
1/**2 * The code façade both handler files call: a project's code read from its3 * canonical repo alone, with main resolved through the project's record.4 * Until 903 and 912 land, each read names the issue that builds it.4 * Until 912 lands, why each line is there names the issue that builds it.5 */6import { describe, expect, it } from "@effect/vitest";7import { RepoHost } from "@repo/artifacts/repo-host";8import type { ProjectApi } from "@repo/project/project";9import {10 CommitSha,11 LandedSha,12 ProjectName,13 RepoPath,14} from "@repo/protocol/ids";9import { LandedSha, ProjectName, RepoPath } from "@repo/protocol/ids";10import { untouchable } from "@repo/testkit/untouchable";11import { Cause, Effect, Exit, Option } from "effect";1218import {19 codeProjectOf,20 commitOf,21 fileOf,22 logOf,23 pathsOf,24 refsOf,25 treeOf,26 whyOf,27} from "../src/code.ts";13import { codeProjectOf, whyOf } from "../src/code.ts";14import { CodeCache } from "../src/code/cache.ts";1516const project = ProjectName.make("datekit");1718const landed = LandedSha.make("4".repeat(40));1934const sha = CommitSha.make("4".repeat(40));3520const path = RepoPath.make("README.md");2122/** A project's record, as the façade reads it: only these three. */23const api = untouchable<ProjectApi>("ProjectApi", {
46 unmodified lines
70 expect(yield* cache.through("datekit:tree:x", read)).toBe(2);71 })72 );7390 it.effect("names the issue that builds each read", () =>74 it.effect("names the issue that builds why each line is there", () =>75 Effect.gen(function* () {92 const none = Option.none();9394 expect(95 yield* Effect.all([96 diedWith(refsOf(code)),97 diedWith(treeOf(code, none, none)),98 diedWith(pathsOf(code, none)),99 diedWith(fileOf(code, none, path)),100 diedWith(logOf(code, { at: none, from: 0, limit: 30, path: none })),101 diedWith(commitOf(code, sha)),102 diedWith(whyOf(code, none, path)),103 ])104 ).toStrictEqual([105 ...Array.from({ length: 6 }, () => Option.some("not built: 903")),106 Option.some("not built: 912"),107 ]);76 expect(yield* diedWith(whyOf(code, Option.none(), path))).toStrictEqual(77 Option.some("not built: 912")78 );79 })80 );81});
added:packages/project/test/code-fixtures.ts+395 added
1/**2 * Repos the code reads are tested over, written object by object with3 * isomorphic-git and pushed to the memory repo host: files of every kind4 * (text, binary, too large, a symlink, a submodule), the refs a canonical5 * repo really carries beside main (the landed mirror, a compose ref, the6 * notes, an import's stale `master`), and tags both lightweight and7 * annotated. Each `CodeProject` is fixed: its head, its one landing and its8 * one fork never come from the repo.9 */10import { RefName, RepoHost } from "@repo/artifacts/repo-host";11import type { RefUpdate } from "@repo/artifacts/repo-host";12import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";13import { Brand } from "@repo/brand";14import type { ForkRef } from "@repo/protocol/domain/code";15import type { LandingView } from "@repo/protocol/domain/landing";16import {17 AskId,18 CommitSha,19 Handle,20 LandedSha,21 ProjectName,22 RepoName,23} from "@repo/protocol/ids";24import { Array, Data, DateTime, Effect, Option } from "effect";25import {26 init,27 writeBlob,28 writeCommit,29 writeTag,30 writeTree,31} from "isomorphic-git";32import type { FsClient, TreeEntry } from "isomorphic-git";3334import type { CodeProject } from "../src/code.ts";3536/** A file's content: text, bytes, a symlink's target, or a submodule's commit. */37export type Content = Data.TaggedEnum<{38 Bytes: { readonly bytes: Uint8Array };39 Gitlink: { readonly commit: string };40 Link: { readonly target: string };41 Text: { readonly text: string };42}>;4344export const Content = Data.taggedEnum<Content>();4546/** Paths and what each holds. */47export type Tree = readonly (readonly [path: string, content: Content])[];4849interface Source {50 readonly fs: FsClient;51 readonly gitdir: string;52}5354const blobOf = (55 source: Source,56 name: string,57 mode: string,58 bytes: Uint8Array59) =>60 Effect.map(61 Effect.promise(() => writeBlob({ ...source, blob: bytes })),62 (oid): TreeEntry => ({ mode, oid, path: name, type: "blob" })63 );6465const entryOf = (source: Source, name: string, content: Content) =>66 Content.$match(content, {67 Bytes: ({ bytes }) => blobOf(source, name, "100644", bytes),68 Gitlink: ({ commit }) =>69 Effect.succeed<TreeEntry>({70 mode: "160000",71 oid: commit,72 path: name,73 type: "commit",74 }),75 Link: ({ target }) =>76 blobOf(source, name, "120000", new TextEncoder().encode(target)),77 Text: ({ text }) =>78 blobOf(source, name, "100644", new TextEncoder().encode(text)),79 });8081const treeOf = (source: Source, files: Tree): Effect.Effect<string> =>82 Effect.gen(function* () {83 const entries: TreeEntry[] = [];84 const nested = new Map<string, [string, Content][]>();8586 for (const [path, content] of files) {87 const [head = path, ...rest] = path.split("/");8889 if (rest.length === 0) {90 entries.push(yield* entryOf(source, head, content));91 } else {92 nested.set(head, [93 ...(nested.get(head) ?? []),94 [rest.join("/"), content],95 ]);96 }97 }9899 for (const [path, inner] of nested) {100 const oid = yield* treeOf(source, inner);101102 entries.push({ mode: "040000", oid, path, type: "tree" });103 }104105 return yield* Effect.promise(() => writeTree({ ...source, tree: entries }));106 });107108/**109 * A bare repo in memory that commits are written to and pushed from, each110 * commit's time `at` seconds after 2026-10-01.111 */112export const writer = Effect.gen(function* () {113 const source = { fs: memoryFs(), gitdir: "/source.git" };114115 yield* Effect.promise(() =>116 init({ ...source, bare: true, defaultBranch: "main" })117 );118119 const commit = (120 message: string,121 files: Tree,122 parents: readonly CommitSha[],123 at: number124 ) =>125 Effect.gen(function* () {126 const tree = yield* treeOf(source, files);127128 const signature = {129 email: "writer@example.com",130 name: "Writer",131 timestamp: 1_790_812_800 + at,132 timezoneOffset: 0,133 };134135 const oid = yield* Effect.promise(() =>136 writeCommit({137 ...source,138 commit: {139 author: signature,140 committer: signature,141 message: `${message}\n`,142 parent: [...parents],143 tree,144 },145 })146 );147148 return CommitSha.make(oid);149 });150151 /** An annotated tag object naming `commit`; its id, as a push sends it. */152 const annotated = (name: string, target: CommitSha) =>153 Effect.map(154 Effect.promise(() =>155 writeTag({156 ...source,157 tag: {158 message: `${name}\n`,159 object: target,160 tag: name,161 tagger: {162 email: "tagger@example.com",163 name: "Tagger",164 timestamp: 1_790_812_800,165 timezoneOffset: 0,166 },167 type: "commit",168 },169 })170 ),171 // SAFETY: a tag's id is a 40-hex object id, which a ref update carries as a commit's.172 (oid) => CommitSha.make(oid)173 );174175 /** `repo` made in the host, holding `refs`, each set to its commit. */176 const push = (177 repo: RepoName,178 refs: readonly (readonly [ref: string, to: CommitSha])[]179 ) =>180 Effect.gen(function* () {181 const host = yield* RepoHost;182183 yield* host.create(repo);184185 const updates = refs.map(([ref, to]): RefUpdate => ({186 from: Option.none(),187 ref: RefName.make(ref),188 to,189 }));190191 if (Array.isReadonlyArrayNonEmpty(updates)) {192 yield* host.push(repo, source, updates);193 }194 }).pipe(Effect.orDie);195196 return { annotated, commit, push };197});198199/** A PNG's signature and the start of its header: a NUL in the first bytes. */200export const png = Uint8Array.of(201 0x89,202 0x50,203 0x4e,204 0x47,205 0x0d,206 0x0a,207 0x1a,208 0x0a,209 0,210 0,211 0,212 0x0d213);214215/** 1.5 MiB of text: past the 1 MiB a file's text may be. */216export const big = `${"x".repeat(1023)}\n`.repeat(1536);217218export const svg =219 '<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>\n';220221export const project = ProjectName.make("datekit");222223const repo = RepoName.make(project);224225const text = (value: string) => Content.Text({ text: value });226227const first: Tree = [228 ["README.md", text("# datekit\n")],229 ["big.txt", text(big)],230 ["feed.xml", text("<feed/>\n")],231 ["latest", Content.Link({ target: "README.md" })],232 ["lib/README.txt", text("upper\n")],233 ["lib/readme.md", text("lower\n")],234 ["logo.png", Content.Bytes({ bytes: png })],235 ["logo.svg", text(svg)],236 ["old.txt", text("old\n")],237 ["page.html", text("<script>alert(1)</script>\n")],238 ["src/a.ts", text("export const a = 1;\n")],239 ["vendor", Content.Gitlink({ commit: "a".repeat(40) })],240];241242const without = (tree: Tree, path: string) =>243 tree.filter(([at]) => at !== path);244245const second: Tree = [246 ...without(without(first, "src/a.ts"), "old.txt"),247 ["new.txt", text("new\n")],248 ["src/a.ts", text("export const a = 2;\n")],249];250251const third: Tree = [252 ...without(second, "README.md"),253 ["README.md", text("# datekit, tidied\n")],254];255256const fourth: Tree = [257 ...without(third, "README.md"),258 ["README.md", text("# datekit, landed\n")],259];260261/** The claim fork the project's record lists. */262export const fork: ForkRef = {263 ask: AskId.make("parse-iso"),264 handle: Handle.make("bob"),265 kind: "claim",266 repo: RepoName.make("datekit--parse-iso--bob"),267};268269/** The project's one landing, on `sha`. */270const landingOf = (sha: CommitSha, parent: CommitSha): LandingView => ({271 ask: AskId.make("parse-iso"),272 assisted: [],273 author: Handle.make("bob"),274 credits: [],275 landedAt: DateTime.makeUnsafe("2026-10-07T12:00:00Z"),276 parent: LandedSha.make(parent),277 project,278 sha: LandedSha.make(sha),279});280281/** A project's record, fixed: main at `head`, `landed` its only landing. */282const recordOf = (283 name: RepoName,284 head: CommitSha,285 landed: readonly LandingView[]286): CodeProject => ({287 forks: Effect.succeed([fork]),288 head: Effect.succeedSome(LandedSha.make(head)),289 landings: (shas) =>290 Effect.succeed(landed.filter(({ sha }) => shas.includes(sha))),291 project: ProjectName.make(name),292 repo: name,293});294295/**296 * datekit, four commits on main: the root; one that modifies `src/a.ts`,297 * deletes `old.txt` and adds `new.txt`; an imported commit whose trailer298 * forges an ask; and the platform's landing. Beside main: `master` at the299 * root (an import's stale branch), the landed mirror, a compose ref, the300 * notes, and three tags (`v1.9.0` light on the root, `v1.10.0` annotated301 * on the second, `@datekit/core@2.0.0` light on the third).302 */303export const datekit = Effect.gen(function* () {304 const git = yield* writer;305 const c1 = yield* git.commit("Start", first, [], 1);306 const c2 = yield* git.commit("Rework a", second, [c1], 2);307308 const c3 = yield* git.commit(309 "Tidy the readme\n\nAsked-by: mallory <mallory@example.com>",310 third,311 [c2],312 3313 );314315 const c4 = yield* git.commit(316 "Land parse-iso\n\nAsked-by: bob <bob@example.com>",317 fourth,318 [c3],319 4320 );321322 const tag = yield* git.annotated("v1.10.0", c2);323324 yield* git.push(repo, [325 ["refs/heads/main", c4],326 ["refs/heads/master", c1],327 [`${Brand.refsPrefix}landed`, c4],328 [`${Brand.refsPrefix}compose/${"b".repeat(40)}`, c3],329 [`refs/notes/${Brand.slug}`, c2],330 ["refs/tags/v1.9.0", c1],331 ["refs/tags/v1.10.0", tag],332 ["refs/tags/@datekit/core@2.0.0", c3],333 ]);334335 return {336 c1,337 c2,338 c3,339 c4,340 code: recordOf(repo, c4, [landingOf(c4, c3)]),341 };342});343344/**345 * A history of `count` commits: the first adds `once.txt`, and every one346 * after changes only `count.txt`.347 */348export const longHistory = (count: number) =>349 Effect.gen(function* () {350 const git = yield* writer;351 const name = RepoName.make("longkit");352 const shas: CommitSha[] = [];353354 for (let at = 1; at <= count; at += 1) {355 const sha = yield* git.commit(356 `Commit ${at}`,357 [358 ["count.txt", text(`${at}\n`)],359 ["once.txt", text("once\n")],360 ],361 shas.slice(-1),362 at363 );364365 shas.push(sha);366 }367368 const head = shas.at(-1) ?? shas[0];369370 if (head === undefined) {371 return yield* Effect.die("no commits");372 }373374 yield* git.push(name, [["refs/heads/main", head]]);375376 return { code: recordOf(name, head, []), shas };377 });378379/** One root commit of `count` files. */380export const wide = (count: number) =>381 Effect.gen(function* () {382 const git = yield* writer;383 const name = RepoName.make("widekit");384385 const sha = yield* git.commit(386 "Many files",387 Array.makeBy(count, (at) => [`f${at}.txt`, text(`${at}\n`)] as const),388 [],389 1390 );391392 yield* git.push(name, [["refs/heads/main", sha]]);393394 return { code: recordOf(name, sha, []), sha };395 });
added:packages/project/test/code-raw.test.ts+187 added
1/**2 * A project's raw bytes as the platform and the dev world serve them: each3 * file under a sandboxing CSP and `nosniff`, typed by its extension so4 * that only images render as themselves (an SVG under the sandbox), markup5 * comes back as plain text, an immutable cache for a commit's id and a6 * minute for a name that moves, and a 404 with nothing from the repo for7 * anything else.8 */9import { describe, expect, it } from "@effect/vitest";10import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";11import { RepoPath } from "@repo/protocol/ids";12import { Effect, Option } from "effect";1314import { treeOf } from "../src/code.ts";15import { rawOf, rawRequestOf, rawRestOf } from "../src/code/raw.ts";16import { datekit, png, svg } from "./code-fixtures.ts";1718const read = (response: Response) =>19 Effect.map(20 Effect.promise(() => response.arrayBuffer()),21 (body) => ({22 body: new Uint8Array(body),23 headers: Object.fromEntries(response.headers.entries()),24 status: response.status,25 })26 );2728describe("a raw file", () => {29 it.effect(30 "at a commit's id is its bytes, sandboxed, unsniffed and cached for good",31 () =>32 Effect.gen(function* () {33 const { c4, code } = yield* datekit;34 const listing = yield* treeOf(code, Option.none(), Option.none());3536 const blob = listing.entries.find(37 ({ name }) => name === "logo.svg"38 )?.sha;3940 const { body, headers, status } = yield* read(41 yield* rawOf(code, c4, RepoPath.make("logo.svg"))42 );4344 expect([status, new TextDecoder().decode(body)]).toStrictEqual([45 200,46 svg,47 ]);48 expect(headers).toMatchObject({49 "cache-control": "public, max-age=31536000, immutable",50 "content-type": "image/svg+xml",51 etag: `"${blob}"`,52 "x-content-type-options": "nosniff",53 });54 expect(headers["content-security-policy"]).toContain("sandbox");55 expect(headers["content-security-policy"]).toContain(56 "default-src 'none'"57 );58 }).pipe(Effect.provide(RepoHostMemory))59 );6061 it.effect("at main or a tag is cached for a minute", () =>62 Effect.gen(function* () {63 const { code } = yield* datekit;6465 const cached = (rev: string) =>66 Effect.map(rawOf(code, rev, RepoPath.make("README.md")), (response) => [67 response.status,68 response.headers.get("cache-control"),69 ]);7071 expect(72 yield* Effect.all([cached("main"), cached("v1.9.0")])73 ).toStrictEqual([74 [200, "public, max-age=60"],75 [200, "public, max-age=60"],76 ]);77 }).pipe(Effect.provide(RepoHostMemory))78 );7980 it.effect(81 "is typed by its extension: images as themselves, markup and the rest as text, binary as bytes",82 () =>83 Effect.gen(function* () {84 const { code } = yield* datekit;8586 const typed = (path: string) =>87 Effect.map(rawOf(code, "main", RepoPath.make(path)), (response) =>88 response.headers.get("content-type")89 );9091 expect(92 yield* Effect.all([93 typed("logo.png"),94 typed("page.html"),95 typed("feed.xml"),96 typed("README.md"),97 ])98 ).toStrictEqual([99 "image/png",100 "text/plain; charset=utf-8",101 "text/plain; charset=utf-8",102 "text/plain; charset=utf-8",103 ]);104105 const image = yield* read(106 yield* rawOf(code, "main", RepoPath.make("logo.png"))107 );108109 expect(image.body).toStrictEqual(png);110 }).pipe(Effect.provide(RepoHostMemory))111 );112113 it.effect(114 "that is missing, a folder, a submodule or at no revision is a 404 with no body",115 () =>116 Effect.gen(function* () {117 const { code } = yield* datekit;118119 const missing = (rev: string, path: string) =>120 Effect.flatMap(rawOf(code, rev, RepoPath.make(path)), read);121122 const answers = yield* Effect.all([123 missing("main", "nope.txt"),124 missing("main", "src"),125 missing("main", "vendor"),126 missing("v9", "README.md"),127 missing("main", "src/../README.md"),128 ]);129130 expect(131 answers.map(({ body, headers, status }) => [132 status,133 body.length,134 headers["x-content-type-options"],135 headers["content-security-policy"]?.endsWith("; sandbox"),136 ])137 ).toStrictEqual(answers.map(() => [404, 0, "nosniff", true]));138 expect(answers).toHaveLength(5);139 }).pipe(Effect.provide(RepoHostMemory))140 );141});142143describe("a raw request's path", () => {144 it("is a revision, then a file's path, each decoded once", () => {145 expect(146 [147 "main/README.md",148 "%40datekit%2Fcore%402.0.0/docs/a%20b.md",149 `${"a".repeat(40)}/src/a.ts`,150 "main",151 "main/",152 "main/src//a.ts",153 "main/../x",154 "main/src/%2E%2E/x",155 "main/..%2Fx",156 "main/%E0%A4%A",157 ].map(rawRequestOf)158 ).toStrictEqual([159 Option.some({ path: "README.md", rev: "main" }),160 Option.some({ path: "docs/a b.md", rev: "@datekit/core@2.0.0" }),161 Option.some({ path: "src/a.ts", rev: "a".repeat(40) }),162 Option.none(),163 Option.none(),164 Option.none(),165 Option.none(),166 Option.none(),167 Option.none(),168 Option.none(),169 ]);170 });171});172173describe("a raw request's URL", () => {174 it("gives everything after the project's raw/, still encoded", () => {175 expect(176 [177 "https://host.example/datekit/raw/%40datekit%2Fcore%402.0.0/README.md",178 "/datekit/raw/main/docs/a%20b.md?plain=1#L2",179 "/datekit/raw/main",180 ].map(rawRestOf)181 ).toStrictEqual([182 "%40datekit%2Fcore%402.0.0/README.md",183 "main/docs/a%20b.md",184 "main",185 ]);186 });187});
added:packages/project/test/code.test.ts+582 added
1/**2 * A project's code as readers browse it, read from its canonical repo over3 * the memory repo host, with main, the landings and the forks taken from a4 * fixed project record: refs without the platform's internals, folders and5 * their READMEs, revisions that resolve only to main, a commit or a tag,6 * files within their caps, the first-parent log with its landings, a7 * commit's changes, and reads by object id kept once read.8 */9import { describe, expect, it } from "@effect/vitest";10import { RepoHost } from "@repo/artifacts/repo-host";11import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";12import { Brand } from "@repo/brand";13import { CommitSha, RepoPath } from "@repo/protocol/ids";14import {15 UnknownCommit,16 UnknownPath,17 UnknownRevision,18} from "@repo/protocol/refusal";19import { DateTime, Effect, Exit, Layer, Option, Ref } from "effect";2021import {22 commitOf,23 fileOf,24 logOf,25 pathsOf,26 refsOf,27 treeOf,28} from "../src/code.ts";29import { CodeCache, CodeCacheLive } from "../src/code/cache.ts";30import { filesUnder } from "../src/code/paths.ts";31import { compareTags } from "../src/code/refs.ts";32import {33 big,34 datekit,35 fork,36 longHistory,37 project,38 wide,39} from "./code-fixtures.ts";4041const revision = (name: string) => Option.some(name);4243const main = Option.none();4445const path = (text: string) => Option.some(RepoPath.make(text));4647const page = { at: main, from: 0, limit: 30, path: Option.none() };4849/**50 * A history of hundreds of commits, written and pushed in memory: well51 * under a second alone, many times that beside every other package's tests.52 */53const long = { timeout: 30_000 };5455describe("a project's refs", () => {56 it.effect(57 "are main's landed commit, its tags newest first and its forks, and nothing of the platform's own",58 () =>59 Effect.gen(function* () {60 const { c1, c2, c3, c4, code } = yield* datekit;6162 expect(yield* refsOf(code)).toStrictEqual({63 forks: [fork],64 landed: c4,65 project,66 tags: [67 { name: "v1.10.0", sha: c2 },68 { name: "v1.9.0", sha: c1 },69 { name: "@datekit/core@2.0.0", sha: c3 },70 ],71 });72 }).pipe(Effect.provide(RepoHostMemory))73 );7475 it("sort by version, newest first, each package's together", () => {76 expect(77 [78 "v1.9.0",79 "v1.10.0",80 "v1.10.0-beta.1",81 "v2.0.0",82 "@changesets/cli@2.27.1",83 "@changesets/cli@2.3.0",84 "@changesets/apply@1.0.0",85 ].toSorted(compareTags)86 ).toStrictEqual([87 "v2.0.0",88 "v1.10.0",89 "v1.10.0-beta.1",90 "v1.9.0",91 "@changesets/cli@2.27.1",92 "@changesets/cli@2.3.0",93 "@changesets/apply@1.0.0",94 ]);95 });96});9798describe("a folder", () => {99 it.effect(100 "lists folders first, then files by name, each by its kind, with its README",101 () =>102 Effect.gen(function* () {103 const { c4, code } = yield* datekit;104 const listing = yield* treeOf(code, main, Option.none());105106 expect(listing.at).toBe(c4);107 expect(listing.path).toBeUndefined();108 expect(109 listing.entries.map(({ name, path: at, type }) => [name, at, type])110 ).toStrictEqual([111 ["lib", "lib", "tree"],112 ["src", "src", "tree"],113 ["README.md", "README.md", "blob"],114 ["big.txt", "big.txt", "blob"],115 ["feed.xml", "feed.xml", "blob"],116 ["latest", "latest", "symlink"],117 ["logo.png", "logo.png", "blob"],118 ["logo.svg", "logo.svg", "blob"],119 ["new.txt", "new.txt", "blob"],120 ["page.html", "page.html", "blob"],121 ["vendor", "vendor", "submodule"],122 ]);123 expect({124 readme: listing.readme,125 vendor: listing.entries.find(({ name }) => name === "vendor"),126 }).toMatchObject({127 readme: {128 path: "README.md",129 sha: listing.entries.find(({ name }) => name === "README.md")?.sha,130 },131 vendor: { mode: "160000", sha: "a".repeat(40) },132 });133 }).pipe(Effect.provide(RepoHostMemory))134 );135136 it.effect("finds a lowercase readme.md before a README.txt", () =>137 Effect.gen(function* () {138 const { code } = yield* datekit;139 const listing = yield* treeOf(code, main, path("lib"));140141 expect(listing.path).toBe("lib");142 expect(listing.entries.map(({ path: at }) => at)).toStrictEqual([143 "lib/README.txt",144 "lib/readme.md",145 ]);146 expect(listing.readme?.path).toBe("lib/readme.md");147 }).pipe(Effect.provide(RepoHostMemory))148 );149150 it.effect("is UnknownPath when missing, or a file", () =>151 Effect.gen(function* () {152 const { c4, code } = yield* datekit;153154 expect(155 yield* Effect.exit(treeOf(code, main, path("nope")))156 ).toStrictEqual(157 Exit.fail(new UnknownPath({ commit: c4, path: RepoPath.make("nope") }))158 );159 expect(160 yield* Effect.exit(treeOf(code, main, path("src/a.ts/x")))161 ).toStrictEqual(162 Exit.fail(163 new UnknownPath({ commit: c4, path: RepoPath.make("src/a.ts/x") })164 )165 );166 expect(167 yield* Effect.exit(treeOf(code, main, path("README.md")))168 ).toStrictEqual(169 Exit.fail(170 new UnknownPath({ commit: c4, path: RepoPath.make("README.md") })171 )172 );173 }).pipe(Effect.provide(RepoHostMemory))174 );175});176177describe("a revision", () => {178 it.effect(179 "is main, a commit the repo holds, or a tag by its exact name, peeled",180 () =>181 Effect.gen(function* () {182 const { c1, c2, c3, c4, code } = yield* datekit;183184 const resolved = (rev: string) =>185 Effect.map(186 treeOf(code, revision(rev), Option.none()),187 ({ at: sha }) => sha188 );189190 expect(191 yield* Effect.all([192 resolved("main"),193 resolved(c1),194 resolved("v1.9.0"),195 resolved("v1.10.0"),196 resolved("@datekit/core@2.0.0"),197 ])198 ).toStrictEqual([c4, c1, c1, c2, c3]);199 }).pipe(Effect.provide(RepoHostMemory))200 );201202 it.effect(203 "is UnknownRevision for anything else, a ref path or another branch included",204 () =>205 Effect.gen(function* () {206 const { code } = yield* datekit;207208 const refused = [209 "v9",210 "master",211 "../heads/master",212 "refs/heads/master",213 "refs/tags/v1.9.0",214 `${Brand.refsPrefix}landed`,215 "f".repeat(40),216 "HEAD",217 ];218219 expect(220 yield* Effect.forEach(refused, (rev) =>221 Effect.exit(treeOf(code, revision(rev), Option.none()))222 )223 ).toStrictEqual(224 refused.map((rev) => Exit.fail(new UnknownRevision({ rev })))225 );226 }).pipe(Effect.provide(RepoHostMemory))227 );228});229230describe("a file", () => {231 it.effect("is its text, with its blob id and size", () =>232 Effect.gen(function* () {233 const { c4, code } = yield* datekit;234 const listing = yield* treeOf(code, main, Option.none());235236 expect(237 yield* fileOf(code, main, RepoPath.make("README.md"))238 ).toStrictEqual({239 at: c4,240 binary: false,241 path: "README.md",242 sha: listing.readme?.sha,243 size: 18,244 text: "# datekit, landed\n",245 truncated: false,246 });247 }).pipe(Effect.provide(RepoHostMemory))248 );249250 it.effect("past 1 MiB is truncated, with no text", () =>251 Effect.gen(function* () {252 const { code } = yield* datekit;253 const file = yield* fileOf(code, main, RepoPath.make("big.txt"));254255 expect(file).toMatchObject({256 binary: false,257 size: big.length,258 truncated: true,259 });260 expect(file.text).toBeUndefined();261 }).pipe(Effect.provide(RepoHostMemory))262 );263264 it.effect("with a NUL among its first bytes is binary, with no text", () =>265 Effect.gen(function* () {266 const { code } = yield* datekit;267 const file = yield* fileOf(code, main, RepoPath.make("logo.png"));268269 expect(file).toMatchObject({ binary: true, size: 12, truncated: false });270 expect(file.text).toBeUndefined();271 }).pipe(Effect.provide(RepoHostMemory))272 );273274 it.effect("is UnknownPath for a folder or a missing path", () =>275 Effect.gen(function* () {276 const { c4, code } = yield* datekit;277278 expect(279 yield* Effect.exit(fileOf(code, main, RepoPath.make("src")))280 ).toStrictEqual(281 Exit.fail(new UnknownPath({ commit: c4, path: RepoPath.make("src") }))282 );283 expect(284 yield* Effect.exit(fileOf(code, main, RepoPath.make("src/b.ts")))285 ).toStrictEqual(286 Exit.fail(287 new UnknownPath({ commit: c4, path: RepoPath.make("src/b.ts") })288 )289 );290 }).pipe(Effect.provide(RepoHostMemory))291 );292});293294describe("every path", () => {295 it.effect("lists each file, symlink and submodule at the revision", () =>296 Effect.gen(function* () {297 const { c1, code } = yield* datekit;298299 expect(yield* pathsOf(code, revision(c1))).toStrictEqual({300 at: c1,301 paths: [302 "README.md",303 "big.txt",304 "feed.xml",305 "latest",306 "lib/README.txt",307 "lib/readme.md",308 "logo.png",309 "logo.svg",310 "old.txt",311 "page.html",312 "src/a.ts",313 "vendor",314 ],315 truncated: false,316 });317 }).pipe(Effect.provide(RepoHostMemory))318 );319});320321describe("every path past the cap", () => {322 it.effect(323 "is the first by path among the folders read before the cap, truncated",324 () =>325 Effect.gen(function* () {326 const { c1, code } = yield* datekit;327 const host = yield* RepoHost;328 const commit = yield* host.readCommit(code.repo, c1);329 const { tree } = Option.getOrThrow(commit);330 const capped = yield* filesUnder(code.repo, tree, 3);331332 // The root alone holds nine files, so no folder below it is read.333 expect({334 paths: capped.files.map(({ path: at }) => at),335 truncated: capped.truncated,336 }).toStrictEqual({337 paths: ["README.md", "big.txt", "feed.xml"],338 truncated: true,339 });340 expect((yield* filesUnder(code.repo, tree, 12)).truncated).toBeFalsy();341 }).pipe(Effect.provide(RepoHostMemory))342 );343});344345describe("the log", () => {346 it.effect(347 "is first parents from the revision, each landing with the platform's record and no other",348 () =>349 Effect.gen(function* () {350 const { c1, c2, c3, c4, code } = yield* datekit;351 const { commits, next } = yield* logOf(code, page);352353 expect(next).toBeUndefined();354 expect(commits.map(({ sha }) => sha)).toStrictEqual([c4, c3, c2, c1]);355356 const [landed, imported] = commits;357358 expect(landed?.landing).toMatchObject({ ask: "parse-iso", sha: c4 });359 expect(imported?.landing).toBeUndefined();360 expect(361 Option.map(Option.fromUndefinedOr(imported), (commit) => ({362 at: DateTime.formatIso(commit.author.at),363 email: commit.author.email,364 name: commit.author.name,365 parents: commit.parents,366 subject: commit.subject,367 trailers: commit.trailers,368 }))369 ).toStrictEqual(370 Option.some({371 at: "2026-10-01T00:00:03.000Z",372 email: "writer@example.com",373 name: "Writer",374 parents: [c2],375 subject: "Tidy the readme",376 trailers: [377 { key: "Asked-by", value: "mallory <mallory@example.com>" },378 ],379 })380 );381 }).pipe(Effect.provide(RepoHostMemory))382 );383384 it.effect(385 "pages 30 at a time, naming where the next page starts",386 () =>387 Effect.gen(function* () {388 const { code, shas } = yield* longHistory(250);389 const first = yield* logOf(code, page);390391 expect(first.commits).toHaveLength(30);392 expect(first.commits[0]?.sha).toBe(shas[249]);393 expect(first.next).toBe(30);394395 const last = yield* logOf(code, { ...page, from: 240 });396397 expect(last.commits.map(({ sha }) => sha)).toStrictEqual(398 shas.slice(0, 10).toReversed()399 );400 expect(last.next).toBeUndefined();401 }).pipe(Effect.provide(RepoHostMemory)),402 long403 );404405 it.effect(406 "for a path, keeps only the commits that changed it, scanning at most 200 a call",407 () =>408 Effect.gen(function* () {409 const { code, shas } = yield* longHistory(250);410 const once = { ...page, path: path("once.txt") };411 const scanned = yield* logOf(code, once);412413 expect(scanned).toStrictEqual({ commits: [], next: 200 });414415 const older = yield* logOf(code, { ...once, from: 200 });416417 expect(older.commits.map(({ sha }) => sha)).toStrictEqual([shas[0]]);418 expect(older.next).toBeUndefined();419420 const counted = yield* logOf(code, {421 ...page,422 limit: 3,423 path: path("count.txt"),424 });425426 expect(counted.commits.map(({ sha }) => sha)).toStrictEqual(427 shas.slice(247).toReversed()428 );429 expect(counted.next).toBe(3);430 }).pipe(Effect.provide(RepoHostMemory)),431 long432 );433});434435describe("a commit", () => {436 it.effect("at the root adds every file", () =>437 Effect.gen(function* () {438 const { c1, code } = yield* datekit;439 const diff = yield* commitOf(code, c1);440441 expect([diff.commit.sha, diff.truncated]).toStrictEqual([c1, false]);442 expect(443 diff.files.map(({ path: at, status }) => [at, status])444 ).toStrictEqual(445 (yield* pathsOf(code, revision(c1))).paths.map((at) => [at, "added"])446 );447 expect(448 diff.files.find(({ path: at }) => at === "src/a.ts")449 ).toMatchObject({ binary: false, newText: "export const a = 1;\n" });450451 const logo = diff.files.find(({ path: at }) => at === "logo.png");452453 expect([logo?.binary, logo?.newText]).toStrictEqual([true, undefined]);454 }).pipe(Effect.provide(RepoHostMemory))455 );456457 it.effect(458 "after it shows each change against the first parent, with both blob ids",459 () =>460 Effect.gen(function* () {461 const { c2, code } = yield* datekit;462 const diff = yield* commitOf(code, c2);463464 expect(465 diff.files.map(({ before, after, path: at, status }) => [466 at,467 status,468 before !== undefined,469 after !== undefined,470 ])471 ).toStrictEqual([472 ["new.txt", "added", false, true],473 ["old.txt", "deleted", true, false],474 ["src/a.ts", "modified", true, true],475 ]);476 expect(477 diff.files.find(({ path: at }) => at === "src/a.ts")478 ).toMatchObject({479 newText: "export const a = 2;\n",480 oldText: "export const a = 1;\n",481 });482 expect(diff.commit.landing).toBeUndefined();483 }).pipe(Effect.provide(RepoHostMemory))484 );485486 it.effect(487 "past 300 files lists paths only, truncated",488 () =>489 Effect.gen(function* () {490 const { code, sha } = yield* wide(301);491 const diff = yield* commitOf(code, sha);492493 expect([diff.truncated, diff.files.length]).toStrictEqual([true, 301]);494 expect(495 diff.files.filter(496 ({ newText, oldText }) =>497 newText !== undefined || oldText !== undefined498 )499 ).toStrictEqual([]);500 }).pipe(Effect.provide(RepoHostMemory)),501 long502 );503504 it.effect("the repo does not hold is UnknownCommit", () =>505 Effect.gen(function* () {506 const { code } = yield* datekit;507 const missing = CommitSha.make("f".repeat(40));508509 expect(yield* Effect.exit(commitOf(code, missing))).toStrictEqual(510 Exit.fail(new UnknownCommit({ sha: missing }))511 );512 }).pipe(Effect.provide(RepoHostMemory))513 );514});515516/** The memory store, with each tree id `readTree` is asked for counted in `reads`. */517const countedBy = (reads: Ref.Ref<readonly string[]>) =>518 Layer.effect(519 RepoHost,520 Effect.gen(function* () {521 const host = yield* RepoHost;522523 return RepoHost.of({524 ...host,525 readTree: (name, tree) =>526 Ref.update(reads, (all) => [...all, tree]).pipe(527 Effect.andThen(host.readTree(name, tree))528 ),529 });530 })531 ).pipe(Layer.provide(RepoHostMemory));532533describe("reads by object id", () => {534 it.effect("are kept once read, while main resolves every time", () =>535 Effect.gen(function* () {536 const reads = yield* Ref.make<readonly string[]>([]);537538 yield* Effect.gen(function* () {539 const { code } = yield* datekit;540 const first = yield* treeOf(code, main, Option.none());541 const counted = (yield* Ref.get(reads)).length;542543 expect(counted).toBeGreaterThan(0);544545 const again = yield* treeOf(code, main, Option.none());546547 expect(again).toStrictEqual(first);548 expect(yield* Ref.get(reads)).toHaveLength(counted);549 }).pipe(550 Effect.provide(Layer.merge(countedBy(reads), CodeCacheLive(100)))551 );552 })553 );554555 it.effect("keep heavy reads apart, so many texts never push out a tree", () =>556 Effect.gen(function* () {557 const cache = yield* CodeCache;558 const reads = yield* Ref.make<readonly string[]>([]);559560 const read = (key: string, heavy: boolean) =>561 cache.through(562 key,563 Ref.update(reads, (all) => [...all, key]),564 { heavy }565 );566567 yield* read("datekit:tree:t", false);568 yield* read("datekit:text:1", true);569 yield* read("datekit:text:2", true);570 yield* read("datekit:tree:t", false);571 yield* read("datekit:text:2", true);572 yield* read("datekit:text:1", true);573574 expect(yield* Ref.get(reads)).toStrictEqual([575 "datekit:tree:t",576 "datekit:text:1",577 "datekit:text:2",578 "datekit:text:1",579 ]);580 }).pipe(Effect.provide(CodeCacheLive(2, 1)))581 );582});