examples.ts
This file
Path
apps/web/src/dev/examples.ts
695 lines · 20.6 KiB · TypeScript
Last changed by
Merge build/1205-dev-fixturesoscabrielbefore adoptionc816189
History of this fileTake it
1/**2 * The dev world's two fictional projects, as files: each one's first push,3 * the files a decider opens each ask with (its ask file, and its check when4 * the check is a file), and the commits its people push. The projects and5 * their people are invented; any likeness to a real one is not meant.6 *7 * `datekit` is a small date library (the people of8 * `examples/datekit`): `ines-v` decides everything, `okonkwo` the time zones, and9 * `bram` is a vouched contributor. `burrow` is a six-package monorepo with10 * a legacy helper to migrate away from and a lint count to ratchet down11 * (`examples/burrow`), decided by `okafor` and `lin-h`. These are12 * cut-down copies: just enough for every page of the web to have something13 * real to show.14 *15 * A project's rules are its committed `policy.json`, the config folder the16 * `/json` rules evaluator reads, with every ask it will open stated there;17 * an ask opens when a decider lands its files. Each ask file is written18 * from the ask `policy.json` states, as the SDK call a maintainer writes,19 * so the two never disagree. datekit's `policy.json` also states the ask20 * the dev world's drafter drafts, which only an accepted draft opens.21 */22import { Brand } from "@repo/brand";23import { cannedDraft } from "@repo/drafting/draft-runs/canned";24import { CheckSpec, RatchetMeasure } from "@repo/protocol/domain/check";25import { Command, SymbolName } from "@repo/protocol/domain/common";26import type { AskKind } from "@repo/protocol/domain/kind";27import { PolicyInput } from "@repo/protocol/domain/policy";28import { AskId, Handle, ProjectName, RepoPath } from "@repo/protocol/ids";29import { Array, Number, Predicate, Schema } from "effect";3031import type { Files } from "./git.ts";3233const dir = Brand.configDir;3435const encodeCheck = Schema.encodeSync(CheckSpec);3637const decodeCheck = Schema.decodeSync(CheckSpec);3839const encodeMeasure = Schema.encodeSync(RatchetMeasure);4041/** What a project's `policy.json` states, as the file holds it. */42export type Stated = typeof PolicyInput.Encoded;4344/** One ask as `policy.json` states it. */45export type StatedAsk = Stated["asks"][number];4647/** A `policy.json` from what its project states, with every default written out. */48export const policyJson = (stated: Stated) =>49 `${JSON.stringify(50 Schema.encodeSync(PolicyInput)(Schema.decodeSync(PolicyInput)(stated)),51 null,52 253 )}\n`;5455/** One file an ask opens with. */56export interface AskFile {57 readonly content: string;58 readonly path: RepoPath;59}6061/** The files a decider opens one ask with: its ask file, then its check's file if it has one. */62export type Opening = Array.NonEmptyReadonlyArray<AskFile>;6364/** The args a kind takes for an ask's check, as its ask file passes them (`packages/sdk`'s `kinds`). */65interface KindArgs {66 readonly command?: string;67 readonly count?: string;68 readonly from?: string;69 readonly path?: string;70 readonly ratchet?: string;71 readonly rule?: string;72 readonly to?: string | undefined;73}7475/** A string, or a list of them, as TypeScript source spells it. */76const spelled = (value: string | readonly string[]): string =>77 Predicate.isString(value)78 ? JSON.stringify(value)79 : `[${value.map(spelled).join(", ")}]`;8081/**82 * The args an ask's kind takes for its check, as the ask file spells them.83 * No SDK call states a `SymbolAbsent` check (a migrate's split opens its84 * delete step), so that file spells the nearest one: a migrate85 * with no `to`, every use gone.86 */87const checkArgs = (check: StatedAsk["check"]) =>88 CheckSpec.match(decodeCheck(check), {89 LintToZero: ({ command, rule }): KindArgs => ({ command, rule }),90 Migrate: ({ count, from, to }): KindArgs => ({ count, from, to }),91 Ratchet: ({ ratchet }): KindArgs => ({ ratchet }),92 RedThenGreen: ({ path }): KindArgs => ({ path }),93 SymbolAbsent: ({ count, symbol }): KindArgs => ({ count, from: symbol }),94 });9596/** An ask's territory as its file spells it: the repo-wide builder for `.`, else the data itself. */97const territoryOf = ({ module, paths }: StatedAsk["territory"]) =>98 module === "."99 ? `territory.paths(${paths.map(spelled).join(", ")})`100 : `{ module: ${spelled(module)}, paths: ${spelled(paths)} }`;101102/** An ask's file: the SDK call that states `stated`, as its maintainer writes it. */103export const askFileOf = (stated: StatedAsk): AskFile => {104 const territory = territoryOf(stated.territory);105106 const passed = Object.entries({107 ...checkArgs(stated.check),108 blockedBy: Array.isReadonlyArrayNonEmpty(stated.blockedBy)109 ? stated.blockedBy110 : undefined,111 current: stated.brief.current,112 mentor: stated.mentor,113 parent: stated.parent,114 reserve: stated.reserve,115 want: stated.brief.want,116 }).flatMap(([key, value]) =>117 value === undefined ? [] : [`${key}: ${spelled(value)}`]118 );119120 const args = [...passed, `territory: ${territory}`].toSorted();121122 const builders = territory.startsWith("territory.")123 ? "kinds, territory"124 : "kinds";125126 return {127 content: [128 `import { ${builders} } from "${Brand.cliPackage}/rules";`,129 "",130 `export default kinds.${stated.kind}.ask({`,131 ...args.map((arg) => ` ${arg},`),132 "});",133 "",134 ].join("\n"),135 path: RepoPath.make(stated.file),136 };137};138139// ------------------------------------------------------------- datekit140141export const datekitPeople = {142 contributor: Handle.make("bram"),143 decider: Handle.make("ines-v"),144 zones: Handle.make("okonkwo"),145} as const;146147const fix = {148 checkKind: "redThenGreen",149 claimers: "vouched",150 finish: "optional",151 name: "fix",152 oneWay: false,153 race: 1,154 requires: ["want", "check", "territory"],155 strength: "assertion",156} satisfies typeof AskKind.Encoded;157158/** One datekit ask: as `policy.json` states it, and the check file it opens with. */159interface DatekitAsk {160 readonly stated: StatedAsk;161 readonly test: AskFile;162}163164/**165 * One datekit ask, from its id, the module file it fixes, its brief and its166 * check's one test (red on main, by an assertion). One held for a newcomer167 * names the maintainer who mentors them. datekit is one package, so every168 * territory is in the repo-wide module, `.`.169 */170const datekitAsk = (input: {171 readonly id: string;172 readonly file: string;173 readonly current: string;174 readonly want: string;175 readonly mentor?: Handle;176 readonly test: {177 readonly imports: readonly string[];178 readonly name: string;179 readonly assertion: string;180 };181}): DatekitAsk => {182 const path = RepoPath.make(`test/asks/${input.id}.test.ts`);183184 const stated: StatedAsk = {185 askedBy: datekitPeople.decider,186 blockedBy: [],187 brief: { current: input.current, want: input.want },188 check: encodeCheck(CheckSpec.cases.RedThenGreen.make({ path })),189 file: `${dir}/asks/${input.id}.ask.ts`,190 id: input.id,191 kind: "fix",192 territory: { module: ".", paths: [`src/${input.file}.ts`] },193 };194195 return {196 stated:197 input.mentor === undefined198 ? stated199 : { ...stated, mentor: input.mentor, reserve: "newcomers" },200 test: {201 content: [202 'import { expect, test } from "bun:test";',203 "",204 ...input.test.imports,205 "",206 `test(${spelled(input.test.name)}, () => {`,207 ` ${input.test.assertion}`,208 "});",209 "",210 ].join("\n"),211 path,212 },213 };214};215216const datekitAsks: readonly DatekitAsk[] = [217 datekitAsk({218 current: "parseISO returns an invalid date for a week date.",219 file: "parse",220 id: "parse-iso-week",221 test: {222 assertion:223 'expect(parseISO("2026-W41-3").toISOString()).toBe("2026-10-07T00:00:00.000Z");',224 imports: ['import { parseISO } from "../../src/parse.ts";'],225 name: "parses an ISO week date",226 },227 want: "parseISO accepts ISO week dates such as 2026-W41-3.",228 }),229 datekitAsk({230 current: 'format prints "11st", "12nd" and "13rd".',231 file: "format",232 id: "format-ordinal",233 // Held for a newcomer, whom its asker mentors.234 mentor: datekitPeople.decider,235 test: {236 assertion: 'expect(format(parseISO("2026-10-11"), "Do")).toBe("11th");',237 imports: [238 'import { format } from "../../src/format.ts";',239 'import { parseISO } from "../../src/parse.ts";',240 ],241 name: "prints the teens as th",242 },243 want: 'format(date, "Do") prints 1st, 2nd, 3rd, 11th, 12th, 13th and 21st.',244 }),245 datekitAsk({246 current: "addMonths(January 31, 1) overflows into March.",247 file: "add",248 id: "add-months-clamp",249 test: {250 assertion:251 'expect(addMonths(parseISO("2026-01-31"), 1).toISOString()).toBe("2026-02-28T00:00:00.000Z");',252 imports: [253 'import { addMonths } from "../../src/add.ts";',254 'import { parseISO } from "../../src/parse.ts";',255 ],256 name: "clamps to the end of February",257 },258 want: "addMonths(January 31, 1) is the last day of February, in leap and common years.",259 }),260 datekitAsk({261 current: "diffInDays counts a day short across the spring change.",262 file: "diff",263 id: "diff-in-days-dst",264 test: {265 assertion:266 'expect(diffInDays(new Date("2026-03-30T00:00:00+02:00"), new Date("2026-03-29T00:00:00+01:00"))).toBe(1);',267 imports: ['import { diffInDays } from "../../src/diff.ts";'],268 name: "counts the spring change as one day",269 },270 want: "diffInDays counts calendar days across a daylight-saving change.",271 }),272];273274/**275 * The ask the dev world's drafter drafts for any want (`cannedDraft`),276 * stated beside datekit's own so the `/json` rules evaluator finds it once277 * a draft's files are composed; nobody opens it in the seed. A decider who278 * accepts the draft opens it.279 */280const draftedAsk: StatedAsk = {281 askedBy: datekitPeople.decider,282 blockedBy: [],283 brief: { current: cannedDraft.current, want: cannedDraft.want },284 check: encodeCheck(285 CheckSpec.cases.RedThenGreen.make({ path: cannedDraft.test.path })286 ),287 file: `${dir}/asks/${cannedDraft.id}.ask.ts`,288 id: cannedDraft.id,289 kind: cannedDraft.kind,290 territory: { module: ".", paths: [...cannedDraft.territory] },291};292293const library: Files = new Map([294 [295 "README.md",296 [297 "# datekit",298 "",299 "Small, dependency-free date helpers: parse, format, add and diff.",300 "",301 "A fictional project: it and its people are invented.",302 "",303 ].join("\n"),304 ],305 [306 "package.json",307 `${JSON.stringify(308 {309 license: "MIT",310 name: "datekit",311 scripts: { test: "bun test", typecheck: "tsc --noEmit" },312 type: "module",313 version: "0.4.2",314 },315 null,316 2317 )}\n`,318 ],319 [320 "src/index.ts",321 [322 'export { addMonths } from "./add.ts";',323 'export { diffInDays } from "./diff.ts";',324 'export { format } from "./format.ts";',325 'export { parseISO } from "./parse.ts";',326 'export { inZone } from "./tz.ts";',327 "",328 ].join("\n"),329 ],330 [331 "src/parse.ts",332 [333 "/** An ISO 8601 date (`2026-10-07`) or date-time, read as UTC. */",334 "export const parseISO = (text: string): Date =>",335 ' new Date(text.length === 10 ? text + "T00:00:00Z" : text);',336 "",337 ].join("\n"),338 ],339 [340 "src/format.ts",341 [342 'const pad = (n: number) => String(n).padStart(2, "0");',343 "",344 'const ordinal = (n: number) => String(n) + (["th", "st", "nd", "rd"][n % 10] ?? "th");',345 "",346 "/** `date` in `pattern`: YYYY, MM, DD and Do (the day as an ordinal). */",347 "export const format = (date: Date, pattern: string): string =>",348 " pattern",349 ' .replaceAll("YYYY", String(date.getUTCFullYear()))',350 ' .replaceAll("MM", pad(date.getUTCMonth() + 1))',351 ' .replaceAll("Do", ordinal(date.getUTCDate()))',352 ' .replaceAll("DD", pad(date.getUTCDate()));',353 "",354 ].join("\n"),355 ],356 [357 "src/add.ts",358 [359 "/** `date` moved by whole months. */",360 "export const addMonths = (date: Date, months: number): Date => {",361 " const next = new Date(date);",362 "",363 " next.setUTCMonth(next.getUTCMonth() + months);",364 "",365 " return next;",366 "};",367 "",368 ].join("\n"),369 ],370 [371 "src/diff.ts",372 [373 "const DAY = 86_400_000;",374 "",375 "/** Whole days from `earlier` to `later`. */",376 "export const diffInDays = (later: Date, earlier: Date): number =>",377 " Math.floor((later.getTime() - earlier.getTime()) / DAY);",378 "",379 ].join("\n"),380 ],381 [382 "src/tz.ts",383 [384 "/** `date` as wall-clock parts in an IANA time zone. */",385 "export const inZone = (date: Date, zone: string) =>",386 ' new Intl.DateTimeFormat("en-CA", { dateStyle: "short", timeStyle: "short", timeZone: zone }).format(date);',387 "",388 ].join("\n"),389 ],390 [391 "test/format.test.ts",392 [393 'import { expect, test } from "bun:test";',394 "",395 'import { format } from "../src/format.ts";',396 'import { parseISO } from "../src/parse.ts";',397 "",398 'test("formats a date", () => {',399 ' expect(format(parseISO("2026-10-07"), "YYYY-MM-DD")).toBe("2026-10-07");',400 "});",401 "",402 ].join("\n"),403 ],404 [405 `${dir}/policy.json`,406 policyJson({407 asks: [...datekitAsks.map(({ stated }) => stated), draftedAsk],408 deciders: [409 { handles: [datekitPeople.decider], paths: "**" },410 { handles: [datekitPeople.zones], paths: "src/tz.ts" },411 ],412 functions: { admit: false, opensAlone: false },413 kinds: [fix],414 ratchets: [],415 run: {416 checks: { types: "bun run typecheck" },417 test: "bun test {path}",418 },419 source: "config",420 weakening: { markers: [".skip(", ".only(", ".todo("] },421 }),422 ],423 [424 `${dir}/vouched.td`,425 [426 "# The people datekit's deciders vouch for.",427 datekitPeople.contributor,428 "",429 ].join("\n"),430 ],431]);432433export const datekit = {434 answer: {435 ask: AskId.make("diff-in-days-dst"),436 files: new Map([437 [438 "src/diff.ts",439 [440 "const DAY = 86_400_000;",441 "",442 "/** Whole calendar days from `earlier` to `later`, across any daylight-saving change. */",443 "export const diffInDays = (later: Date, earlier: Date): number =>",444 " Math.round((later.getTime() - earlier.getTime()) / DAY);",445 "",446 ].join("\n"),447 ],448 ]) satisfies Files,449 message: "Count calendar days across a daylight-saving change",450 },451 asks: datekitAsks.map(452 ({ stated, test }) =>453 [AskId.make(stated.id), [askFileOf(stated), test]] as const454 ),455 files: library,456 project: ProjectName.make("datekit"),457 /** A commit someone pushed straight to main, past the platform. */458 stray: {459 files: new Map([460 [461 "README.md",462 [463 "# datekit",464 "",465 "Small, dependency-free date helpers: parse, format, add, diff and time zones.",466 "",467 "A fictional project: it and its people are invented.",468 "",469 ].join("\n"),470 ],471 ]) satisfies Files,472 message: "Mention time zones in the README",473 },474} as const;475476// -------------------------------------------------------------- burrow477478export const burrowPeople = {479 decider: Handle.make("okafor"),480 second: Handle.make("lin-h"),481} as const;482483const PACKAGES = [484 "kit",485 "auth",486 "billing",487 "catalog",488 "notify",489 "search",490] as const;491492const COUNT = "bun scripts/count-callers.ts legacyFetch --json";493494const migrateCheck = encodeCheck(495 CheckSpec.cases.Migrate.make({496 count: Command.make(COUNT),497 from: SymbolName.make("legacyFetch"),498 to: SymbolName.make("http.get"),499 })500);501502const PARENT = "drop-legacy-fetch";503504/**505 * The one ask burrow's decider opens: the migrate. Its callers sit in all506 * six packages, so the platform opens it as a family: a child507 * per package and a delete child waiting on the six, their files written508 * beside the parent's in the same landing.509 */510const burrowAsks: readonly StatedAsk[] = [511 {512 askedBy: burrowPeople.decider,513 blockedBy: [],514 brief: {515 want: "Replace every call to legacyFetch with http.get, then delete legacyFetch.",516 },517 check: migrateCheck,518 file: `${dir}/asks/${PARENT}.ask.ts`,519 id: PARENT,520 kind: "migrate",521 territory: {522 module: ".",523 paths: Array.map(PACKAGES, (pkg) => `packages/${pkg}/**`),524 },525 },526];527528const packageFiles = (pkg: string): readonly (readonly [string, string])[] => [529 [530 `packages/${pkg}/package.json`,531 `${JSON.stringify(532 {533 exports: { ".": "./src/index.ts" },534 name: `@burrow/${pkg}`,535 type: "module",536 },537 null,538 2539 )}\n`,540 ],541 [542 `packages/${pkg}/src/index.ts`,543 pkg === "kit"544 ? [545 "/** The old way to fetch: kept until nothing calls it. */",546 "export const legacyFetch = (url: string) => fetch(url).then((response) => response.json());",547 "",548 "export const http = { get: (url: string) => fetch(url).then((response) => response.json()) };",549 "",550 "let calls = 0;",551 "",552 'export const ping = () => legacyFetch("/kit/ping?n=" + String((calls += 1)));',553 "",554 ].join("\n")555 : [556 'import { legacyFetch } from "@burrow/kit";',557 "",558 "let cache: unknown;",559 "",560 `export const load = async () => (cache ??= await legacyFetch("/${pkg}"));`,561 "",562 ].join("\n"),563 ],564];565566const monorepo: Files = new Map([567 [568 "README.md",569 [570 "# burrow",571 "",572 "Six packages that share a kit, a lint setup and a debt counter.",573 "",574 "A fictional project: it and its people are invented.",575 "",576 ].join("\n"),577 ],578 [579 "package.json",580 `${JSON.stringify(581 {582 name: "burrow",583 private: true,584 scripts: { lint: "oxlint", test: "bun test" },585 workspaces: ["packages/*"],586 },587 null,588 2589 )}\n`,590 ],591 [592 "scripts/count-callers.ts",593 [594 "// Prints how many times each package calls a symbol, as JSON.",595 'import { Glob } from "bun";',596 "",597 "const [symbol] = Bun.argv.slice(2);",598 "const byModule: Record<string, number> = {};",599 "",600 'for await (const path of new Glob("packages/*/src/**/*.ts").scan()) {',601 ' const name = "@burrow/" + path.split("/")[1];',602 " const text = await Bun.file(path).text();",603 "",604 ' byModule[name] = (byModule[name] ?? 0) + (text.split(symbol + "(").length - 1);',605 "}",606 "",607 "const total = Object.values(byModule).reduce((sum, n) => sum + n, 0);",608 "",609 "console.log(JSON.stringify({ byModule, total }));",610 "",611 ].join("\n"),612 ],613 ...PACKAGES.flatMap(packageFiles),614 [615 `${dir}/policy.json`,616 policyJson({617 asks: burrowAsks,618 deciders: [619 {620 handles: [burrowPeople.decider, burrowPeople.second],621 paths: "**",622 },623 ],624 functions: { admit: false, opensAlone: false },625 kinds: [626 {627 checkKind: "migrate",628 claimers: "vouched",629 finish: "never",630 name: "migrate",631 oneWay: false,632 race: 1,633 requires: ["want", "check", "territory"],634 strength: "assertion",635 },636 ],637 ratchets: [638 {639 measure: encodeMeasure(640 RatchetMeasure.cases.Count.make({641 command: Command.make("bun run lint --format json"),642 rule: "burrow/no-module-level-mutable-state",643 })644 ),645 name: "mutable-state",646 },647 ],648 run: { checks: { lint: "bun run lint" }, test: "bun test {path}" },649 source: "config",650 weakening: { markers: [".skip(", ".only(", ".todo("] },651 }),652 ],653 [`${dir}/vouched.td`, "# The people burrow's deciders vouch for.\n"],654]);655656export const burrow = {657 asks: burrowAsks.map(658 (stated) => [AskId.make(stated.id), [askFileOf(stated)]] as const659 ),660 files: monorepo,661 project: ProjectName.make("burrow"),662} as const;663664/** How many times `text` calls `symbol`, as burrow's `scripts/count-callers.ts` counts. */665const callsIn = (text: string, symbol: string) =>666 text.split(`${symbol}(`).length - 1;667668/** What burrow's count command prints on its first commit: each package's calls of `legacyFetch`. */669const burrowCallers = () => {670 const byModule = Object.fromEntries(671 PACKAGES.map((pkg) => [672 `@burrow/${pkg}`,673 Number.sumAll(674 [...monorepo].flatMap(([path, text]) =>675 path.startsWith(`packages/${pkg}/src/`)676 ? [callsIn(text, "legacyFetch")]677 : []678 )679 ),680 ])681 );682683 return JSON.stringify({684 byModule,685 total: Number.sumAll(Object.values(byModule)),686 });687};688689/**690 * What each count command of the examples prints, by the command: the dev691 * Checker runs none, so a count lane prints this wherever it runs.692 */693export const printedBy: ReadonlyMap<string, string> = new Map([694 [COUNT, burrowCallers()],695]);