examples.ts
This file
Path
apps/web/src/dev/examples.ts
632 lines · 17.3 KiB · TypeScript
Last changed by
Merge build/maintainer-wording into mainoscabrielbefore adoption4c1a571
History of this fileTake it
The walk stopped after 200 commits: lines older than 678c8b8 point at it.
Merge build/comments-web-rest into mainoscabrielbefore adoption0eb1248
line 1why, one step back1// The projects and their people are invented; any likeness to a real one is not meant.Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
line 2why, one step back2import { Brand } from "@repo/brand";Merge branch 'build/910-draft-workflow'oscabrielbefore adoptiona0c8f4f
line 3why, one step back3import { cannedDraft } from "@repo/drafting/draft-runs/canned";Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 4–20why, one step back4import { CheckSpec, RatchetMeasure } from "@repo/protocol/domain/check";5import { Command, SymbolName } from "@repo/protocol/domain/common";6import type { AskKind } from "@repo/protocol/domain/kind";7import { PolicyInput } from "@repo/protocol/domain/policy";8import { AskId, Handle, ProjectName, RepoPath } from "@repo/protocol/ids";9import { Array, Number, Predicate, Schema } from "effect";1011import type { Files } from "./git.ts";1213const dir = Brand.configDir;1415const encodeCheck = Schema.encodeSync(CheckSpec);1617const decodeCheck = Schema.decodeSync(CheckSpec);1819const encodeMeasure = Schema.encodeSync(RatchetMeasure);20Merge build/1205-dev-fixturesoscabrielbefore adoptionc816189
line 21why, one step back21export type Stated = typeof PolicyInput.Encoded;Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
line 22why, one step back22Merge build/1205-dev-fixturesoscabrielbefore adoptionc816189
line 23why, one step back23export type StatedAsk = Stated["asks"][number];Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
line 24why, one step back24Merge build/1205-dev-fixturesoscabrielbefore adoptionc816189
line 25why, one step back25export const policyJson = (stated: Stated) =>Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 26–31why, one step back26 `${JSON.stringify(27 Schema.encodeSync(PolicyInput)(Schema.decodeSync(PolicyInput)(stated)),28 null,29 230 )}\n`;31Merge build/1205-dev-fixturesoscabrielbefore adoptionc816189
line 32why, one step back32export interface AskFile {Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 33–53why, one step back33 readonly content: string;34 readonly path: RepoPath;35}3637export type Opening = Array.NonEmptyReadonlyArray<AskFile>;3839interface KindArgs {40 readonly command?: string;41 readonly count?: string;42 readonly from?: string;43 readonly path?: string;44 readonly ratchet?: string;45 readonly rule?: string;46 readonly to?: string | undefined;47}4849const spelled = (value: string | readonly string[]): string =>50 Predicate.isString(value)51 ? JSON.stringify(value)52 : `[${value.map(spelled).join(", ")}]`;53Merge build/comments-web-rest into mainoscabrielbefore adoption0eb1248
line 54why, one step back54// No SDK call states a `SymbolAbsent` check, so the file spells the nearest one: a migrate with no `to`.Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 55–68why, one step back55const checkArgs = (check: StatedAsk["check"]) =>56 CheckSpec.match(decodeCheck(check), {57 LintToZero: ({ command, rule }): KindArgs => ({ command, rule }),58 Migrate: ({ count, from, to }): KindArgs => ({ count, from, to }),59 Ratchet: ({ ratchet }): KindArgs => ({ ratchet }),60 RedThenGreen: ({ path }): KindArgs => ({ path }),61 SymbolAbsent: ({ count, symbol }): KindArgs => ({ count, from: symbol }),62 });6364const territoryOf = ({ module, paths }: StatedAsk["territory"]) =>65 module === "."66 ? `territory.paths(${paths.map(spelled).join(", ")})`67 : `{ module: ${spelled(module)}, paths: ${spelled(paths)} }`;68Merge build/1205-dev-fixturesoscabrielbefore adoptionc816189
line 69why, one step back69export const askFileOf = (stated: StatedAsk): AskFile => {Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 70–104why, one step back70 const territory = territoryOf(stated.territory);7172 const passed = Object.entries({73 ...checkArgs(stated.check),74 blockedBy: Array.isReadonlyArrayNonEmpty(stated.blockedBy)75 ? stated.blockedBy76 : undefined,77 current: stated.brief.current,78 mentor: stated.mentor,79 parent: stated.parent,80 reserve: stated.reserve,81 want: stated.brief.want,82 }).flatMap(([key, value]) =>83 value === undefined ? [] : [`${key}: ${spelled(value)}`]84 );8586 const args = [...passed, `territory: ${territory}`].toSorted();8788 const builders = territory.startsWith("territory.")89 ? "kinds, territory"90 : "kinds";9192 return {93 content: [94 `import { ${builders} } from "${Brand.cliPackage}/rules";`,95 "",96 `export default kinds.${stated.kind}.ask({`,97 ...args.map((arg) => ` ${arg},`),98 "});",99 "",100 ].join("\n"),101 path: RepoPath.make(stated.file),102 };103};104Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
lines 105–106why, one step back105export const operator = Handle.make("oscabriel");106Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 107–231why, one step back107export const datekitPeople = {108 contributor: Handle.make("bram"),109 decider: Handle.make("ines-v"),110 zones: Handle.make("okonkwo"),111} as const;112113const fix = {114 checkKind: "redThenGreen",115 claimers: "vouched",116 finish: "optional",117 name: "fix",118 oneWay: false,119 race: 1,120 requires: ["want", "check", "territory"],121 strength: "assertion",122} satisfies typeof AskKind.Encoded;123124interface DatekitAsk {125 readonly stated: StatedAsk;126 readonly test: AskFile;127}128129const datekitAsk = (input: {130 readonly id: string;131 readonly file: string;132 readonly current: string;133 readonly want: string;134 readonly mentor?: Handle;135 readonly test: {136 readonly imports: readonly string[];137 readonly name: string;138 readonly assertion: string;139 };140}): DatekitAsk => {141 const path = RepoPath.make(`test/asks/${input.id}.test.ts`);142143 const stated: StatedAsk = {144 askedBy: datekitPeople.decider,145 blockedBy: [],146 brief: { current: input.current, want: input.want },147 check: encodeCheck(CheckSpec.cases.RedThenGreen.make({ path })),148 file: `${dir}/asks/${input.id}.ask.ts`,149 id: input.id,150 kind: "fix",151 territory: { module: ".", paths: [`src/${input.file}.ts`] },152 };153154 return {155 stated:156 input.mentor === undefined157 ? stated158 : { ...stated, mentor: input.mentor, reserve: "newcomers" },159 test: {160 content: [161 'import { expect, test } from "bun:test";',162 "",163 ...input.test.imports,164 "",165 `test(${spelled(input.test.name)}, () => {`,166 ` ${input.test.assertion}`,167 "});",168 "",169 ].join("\n"),170 path,171 },172 };173};174175const datekitAsks: readonly DatekitAsk[] = [176 datekitAsk({177 current: "parseISO returns an invalid date for a week date.",178 file: "parse",179 id: "parse-iso-week",180 test: {181 assertion:182 'expect(parseISO("2026-W41-3").toISOString()).toBe("2026-10-07T00:00:00.000Z");',183 imports: ['import { parseISO } from "../../src/parse.ts";'],184 name: "parses an ISO week date",185 },186 want: "parseISO accepts ISO week dates such as 2026-W41-3.",187 }),188 datekitAsk({189 current: 'format prints "11st", "12nd" and "13rd".',190 file: "format",191 id: "format-ordinal",192 mentor: datekitPeople.decider,193 test: {194 assertion: 'expect(format(parseISO("2026-10-11"), "Do")).toBe("11th");',195 imports: [196 'import { format } from "../../src/format.ts";',197 'import { parseISO } from "../../src/parse.ts";',198 ],199 name: "prints the teens as th",200 },201 want: 'format(date, "Do") prints 1st, 2nd, 3rd, 11th, 12th, 13th and 21st.',202 }),203 datekitAsk({204 current: "addMonths(January 31, 1) overflows into March.",205 file: "add",206 id: "add-months-clamp",207 test: {208 assertion:209 'expect(addMonths(parseISO("2026-01-31"), 1).toISOString()).toBe("2026-02-28T00:00:00.000Z");',210 imports: [211 'import { addMonths } from "../../src/add.ts";',212 'import { parseISO } from "../../src/parse.ts";',213 ],214 name: "clamps to the end of February",215 },216 want: "addMonths(January 31, 1) is the last day of February, in leap and common years.",217 }),218 datekitAsk({219 current: "diffInDays counts a day short across the spring change.",220 file: "diff",221 id: "diff-in-days-dst",222 test: {223 assertion:224 'expect(diffInDays(new Date("2026-03-30T00:00:00+02:00"), new Date("2026-03-29T00:00:00+01:00"))).toBe(1);',225 imports: ['import { diffInDays } from "../../src/diff.ts";'],226 name: "counts the spring change as one day",227 },228 want: "diffInDays counts calendar days across a daylight-saving change.",229 }),230];231Merge branch 'build/910-draft-workflow'oscabrielbefore adoptiona0c8f4f
lines 232–244why, one step back232const draftedAsk: StatedAsk = {233 askedBy: datekitPeople.decider,234 blockedBy: [],235 brief: { current: cannedDraft.current, want: cannedDraft.want },236 check: encodeCheck(237 CheckSpec.cases.RedThenGreen.make({ path: cannedDraft.test.path })238 ),239 file: `${dir}/asks/${cannedDraft.id}.ask.ts`,240 id: cannedDraft.id,241 kind: cannedDraft.kind,242 territory: { module: ".", paths: [...cannedDraft.territory] },243};244Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 245–358why, one step back245const library: Files = new Map([246 [247 "README.md",248 [249 "# datekit",250 "",251 "Small, dependency-free date helpers: parse, format, add and diff.",252 "",253 "A fictional project: it and its people are invented.",254 "",255 ].join("\n"),256 ],257 [258 "package.json",259 `${JSON.stringify(260 {261 license: "MIT",262 name: "datekit",263 scripts: { test: "bun test", typecheck: "tsc --noEmit" },264 type: "module",265 version: "0.4.2",266 },267 null,268 2269 )}\n`,270 ],271 [272 "src/index.ts",273 [274 'export { addMonths } from "./add.ts";',275 'export { diffInDays } from "./diff.ts";',276 'export { format } from "./format.ts";',277 'export { parseISO } from "./parse.ts";',278 'export { inZone } from "./tz.ts";',279 "",280 ].join("\n"),281 ],282 [283 "src/parse.ts",284 [285 "/** An ISO 8601 date (`2026-10-07`) or date-time, read as UTC. */",286 "export const parseISO = (text: string): Date =>",287 ' new Date(text.length === 10 ? text + "T00:00:00Z" : text);',288 "",289 ].join("\n"),290 ],291 [292 "src/format.ts",293 [294 'const pad = (n: number) => String(n).padStart(2, "0");',295 "",296 'const ordinal = (n: number) => String(n) + (["th", "st", "nd", "rd"][n % 10] ?? "th");',297 "",298 "/** `date` in `pattern`: YYYY, MM, DD and Do (the day as an ordinal). */",299 "export const format = (date: Date, pattern: string): string =>",300 " pattern",301 ' .replaceAll("YYYY", String(date.getUTCFullYear()))',302 ' .replaceAll("MM", pad(date.getUTCMonth() + 1))',303 ' .replaceAll("Do", ordinal(date.getUTCDate()))',304 ' .replaceAll("DD", pad(date.getUTCDate()));',305 "",306 ].join("\n"),307 ],308 [309 "src/add.ts",310 [311 "/** `date` moved by whole months. */",312 "export const addMonths = (date: Date, months: number): Date => {",313 " const next = new Date(date);",314 "",315 " next.setUTCMonth(next.getUTCMonth() + months);",316 "",317 " return next;",318 "};",319 "",320 ].join("\n"),321 ],322 [323 "src/diff.ts",324 [325 "const DAY = 86_400_000;",326 "",327 "/** Whole days from `earlier` to `later`. */",328 "export const diffInDays = (later: Date, earlier: Date): number =>",329 " Math.floor((later.getTime() - earlier.getTime()) / DAY);",330 "",331 ].join("\n"),332 ],333 [334 "src/tz.ts",335 [336 "/** `date` as wall-clock parts in an IANA time zone. */",337 "export const inZone = (date: Date, zone: string) =>",338 ' new Intl.DateTimeFormat("en-CA", { dateStyle: "short", timeStyle: "short", timeZone: zone }).format(date);',339 "",340 ].join("\n"),341 ],342 [343 "test/format.test.ts",344 [345 'import { expect, test } from "bun:test";',346 "",347 'import { format } from "../src/format.ts";',348 'import { parseISO } from "../src/parse.ts";',349 "",350 'test("formats a date", () => {',351 ' expect(format(parseISO("2026-10-07"), "YYYY-MM-DD")).toBe("2026-10-07");',352 "});",353 "",354 ].join("\n"),355 ],356 [357 `${dir}/policy.json`,358 policyJson({Merge branch 'build/910-draft-workflow'oscabrielbefore adoptiona0c8f4f
line 359why, one step back359 asks: [...datekitAsks.map(({ stated }) => stated), draftedAsk],Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 360–377why, one step back360 deciders: [361 { handles: [datekitPeople.decider], paths: "**" },362 { handles: [datekitPeople.zones], paths: "src/tz.ts" },363 ],364 functions: { admit: false, opensAlone: false },365 kinds: [fix],366 ratchets: [],367 run: {368 checks: { types: "bun run typecheck" },369 test: "bun test {path}",370 },371 source: "config",372 weakening: { markers: [".skip(", ".only(", ".todo("] },373 }),374 ],375 [376 `${dir}/vouched.td`,377 [Merge build/maintainer-wording into mainoscabrielbefore adoption4c1a571
line 378why, one step back378 "# The people datekit's maintainers vouch for.",Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 379–407why, one step back379 datekitPeople.contributor,380 "",381 ].join("\n"),382 ],383]);384385export const datekit = {386 answer: {387 ask: AskId.make("diff-in-days-dst"),388 files: new Map([389 [390 "src/diff.ts",391 [392 "const DAY = 86_400_000;",393 "",394 "/** Whole calendar days from `earlier` to `later`, across any daylight-saving change. */",395 "export const diffInDays = (later: Date, earlier: Date): number =>",396 " Math.round((later.getTime() - earlier.getTime()) / DAY);",397 "",398 ].join("\n"),399 ],400 ]) satisfies Files,401 message: "Count calendar days across a daylight-saving change",402 },403 asks: datekitAsks.map(404 ({ stated, test }) =>405 [AskId.make(stated.id), [askFileOf(stated), test]] as const406 ),407 files: library,Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 408why, one step back408 project: ProjectName.make("oscabriel/datekit"),Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 409–595why, one step back409 stray: {410 files: new Map([411 [412 "README.md",413 [414 "# datekit",415 "",416 "Small, dependency-free date helpers: parse, format, add, diff and time zones.",417 "",418 "A fictional project: it and its people are invented.",419 "",420 ].join("\n"),421 ],422 ]) satisfies Files,423 message: "Mention time zones in the README",424 },425} as const;426427export const burrowPeople = {428 decider: Handle.make("okafor"),429 second: Handle.make("lin-h"),430} as const;431432const PACKAGES = [433 "kit",434 "auth",435 "billing",436 "catalog",437 "notify",438 "search",439] as const;440441const COUNT = "bun scripts/count-callers.ts legacyFetch --json";442443const migrateCheck = encodeCheck(444 CheckSpec.cases.Migrate.make({445 count: Command.make(COUNT),446 from: SymbolName.make("legacyFetch"),447 to: SymbolName.make("http.get"),448 })449);450451const PARENT = "drop-legacy-fetch";452453const burrowAsks: readonly StatedAsk[] = [454 {455 askedBy: burrowPeople.decider,456 blockedBy: [],457 brief: {458 want: "Replace every call to legacyFetch with http.get, then delete legacyFetch.",459 },460 check: migrateCheck,461 file: `${dir}/asks/${PARENT}.ask.ts`,462 id: PARENT,463 kind: "migrate",464 territory: {465 module: ".",466 paths: Array.map(PACKAGES, (pkg) => `packages/${pkg}/**`),467 },468 },469];470471const packageFiles = (pkg: string): readonly (readonly [string, string])[] => [472 [473 `packages/${pkg}/package.json`,474 `${JSON.stringify(475 {476 exports: { ".": "./src/index.ts" },477 name: `@burrow/${pkg}`,478 type: "module",479 },480 null,481 2482 )}\n`,483 ],484 [485 `packages/${pkg}/src/index.ts`,486 pkg === "kit"487 ? [488 "/** The old way to fetch: kept until nothing calls it. */",489 "export const legacyFetch = (url: string) => fetch(url).then((response) => response.json());",490 "",491 "export const http = { get: (url: string) => fetch(url).then((response) => response.json()) };",492 "",493 "let calls = 0;",494 "",495 'export const ping = () => legacyFetch("/kit/ping?n=" + String((calls += 1)));',496 "",497 ].join("\n")498 : [499 'import { legacyFetch } from "@burrow/kit";',500 "",501 "let cache: unknown;",502 "",503 `export const load = async () => (cache ??= await legacyFetch("/${pkg}"));`,504 "",505 ].join("\n"),506 ],507];508509const monorepo: Files = new Map([510 [511 "README.md",512 [513 "# burrow",514 "",515 "Six packages that share a kit, a lint setup and a debt counter.",516 "",517 "A fictional project: it and its people are invented.",518 "",519 ].join("\n"),520 ],521 [522 "package.json",523 `${JSON.stringify(524 {525 name: "burrow",526 private: true,527 scripts: { lint: "oxlint", test: "bun test" },528 workspaces: ["packages/*"],529 },530 null,531 2532 )}\n`,533 ],534 [535 "scripts/count-callers.ts",536 [537 "// Prints how many times each package calls a symbol, as JSON.",538 'import { Glob } from "bun";',539 "",540 "const [symbol] = Bun.argv.slice(2);",541 "const byModule: Record<string, number> = {};",542 "",543 'for await (const path of new Glob("packages/*/src/**/*.ts").scan()) {',544 ' const name = "@burrow/" + path.split("/")[1];',545 " const text = await Bun.file(path).text();",546 "",547 ' byModule[name] = (byModule[name] ?? 0) + (text.split(symbol + "(").length - 1);',548 "}",549 "",550 "const total = Object.values(byModule).reduce((sum, n) => sum + n, 0);",551 "",552 "console.log(JSON.stringify({ byModule, total }));",553 "",554 ].join("\n"),555 ],556 ...PACKAGES.flatMap(packageFiles),557 [558 `${dir}/policy.json`,559 policyJson({560 asks: burrowAsks,561 deciders: [562 {563 handles: [burrowPeople.decider, burrowPeople.second],564 paths: "**",565 },566 ],567 functions: { admit: false, opensAlone: false },568 kinds: [569 {570 checkKind: "migrate",571 claimers: "vouched",572 finish: "never",573 name: "migrate",574 oneWay: false,575 race: 1,576 requires: ["want", "check", "territory"],577 strength: "assertion",578 },579 ],580 ratchets: [581 {582 measure: encodeMeasure(583 RatchetMeasure.cases.Count.make({584 command: Command.make("bun run lint --format json"),585 rule: "burrow/no-module-level-mutable-state",586 })587 ),588 name: "mutable-state",589 },590 ],591 run: { checks: { lint: "bun run lint" }, test: "bun test {path}" },592 source: "config",593 weakening: { markers: [".skip(", ".only(", ".todo("] },594 }),595 ],Merge build/maintainer-wording into mainoscabrielbefore adoption4c1a571
line 596why, one step back596 [`${dir}/vouched.td`, "# The people burrow's maintainers vouch for.\n"],Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 597–603why, one step back597]);598599export const burrow = {600 asks: burrowAsks.map(601 (stated) => [AskId.make(stated.id), [askFileOf(stated)]] as const602 ),603 files: monorepo,Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 604why, one step back604 project: ProjectName.make("oscabriel/burrow"),Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 605–632why, one step back605} as const;606607const callsIn = (text: string, symbol: string) =>608 text.split(`${symbol}(`).length - 1;609610const burrowCallers = () => {611 const byModule = Object.fromEntries(612 PACKAGES.map((pkg) => [613 `@burrow/${pkg}`,614 Number.sumAll(615 [...monorepo].flatMap(([path, text]) =>616 path.startsWith(`packages/${pkg}/src/`)617 ? [callsIn(text, "legacyFetch")]618 : []619 )620 ),621 ])622 );623624 return JSON.stringify({625 byModule,626 total: Number.sumAll(Object.values(byModule)),627 });628};629630export const printedBy: ReadonlyMap<string, string> = new Map([631 [COUNT, burrowCallers()],632]);