examples.ts
This file
Path
apps/web/src/dev/examples.ts
686 lines · 19.2 KiB · TypeScript
Last changed by
Merge project/drop-proposals into mainoscabrielbefore adoptionb4ed08b
History of this fileTake it
The walk stopped after 200 commits: lines older than f9808ff 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.Tell stage 1 a pusher reads the layers only when they read every one, and give the no-oracle path rule one owner in the gateoscabrielbefore adoptionf9808ff
lines 2–19why, one step back2import { Brand } from "@repo/brand";3import { CheckSpec, RatchetMeasure } from "@repo/protocol/domain/check";4import { Command, SymbolName } from "@repo/protocol/domain/common";5import type { AskKind } from "@repo/protocol/domain/kind";6import { PolicyInput } from "@repo/protocol/domain/policy";7import { AskId, Handle, ProjectName, RepoPath } from "@repo/protocol/ids";8import { Array, Number, Predicate, Schema } from "effect";910import type { Files } from "./git.ts";1112const dir = Brand.configDir;1314const encodeCheck = Schema.encodeSync(CheckSpec);1516const decodeCheck = Schema.decodeSync(CheckSpec);1718const encodeMeasure = Schema.encodeSync(RatchetMeasure);19Merge build/1205-dev-fixturesoscabrielbefore adoptionc816189
line 20why, one step back20export type Stated = typeof PolicyInput.Encoded;Tell stage 1 a pusher reads the layers only when they read every one, and give the no-oracle path rule one owner in the gateoscabrielbefore adoptionf9808ff
line 21why, one step back21Merge build/1205-dev-fixturesoscabrielbefore adoptionc816189
line 22why, one step back22export type StatedAsk = Stated["asks"][number];Tell stage 1 a pusher reads the layers only when they read every one, and give the no-oracle path rule one owner in the gateoscabrielbefore adoptionf9808ff
line 23why, one step back23Merge build/1205-dev-fixturesoscabrielbefore adoptionc816189
line 24why, one step back24export const policyJson = (stated: Stated) =>Tell stage 1 a pusher reads the layers only when they read every one, and give the no-oracle path rule one owner in the gateoscabrielbefore adoptionf9808ff
lines 25–30why, one step back25 `${JSON.stringify(26 Schema.encodeSync(PolicyInput)(Schema.decodeSync(PolicyInput)(stated)),27 null,28 229 )}\n`;30Merge build/1205-dev-fixturesoscabrielbefore adoptionc816189
line 31why, one step back31export interface AskFile {Tell stage 1 a pusher reads the layers only when they read every one, and give the no-oracle path rule one owner in the gateoscabrielbefore adoptionf9808ff
lines 32–52why, one step back32 readonly content: string;33 readonly path: RepoPath;34}3536export type Opening = Array.NonEmptyReadonlyArray<AskFile>;3738interface KindArgs {39 readonly command?: string;40 readonly count?: string;41 readonly from?: string;42 readonly path?: string;43 readonly ratchet?: string;44 readonly rule?: string;45 readonly to?: string | undefined;46}4748const spelled = (value: string | readonly string[]): string =>49 Predicate.isString(value)50 ? JSON.stringify(value)51 : `[${value.map(spelled).join(", ")}]`;52Merge build/comments-web-rest into mainoscabrielbefore adoption0eb1248
line 53why, one step back53// No SDK call states a `SymbolAbsent` check, so the file spells the nearest one: a migrate with no `to`.Tell stage 1 a pusher reads the layers only when they read every one, and give the no-oracle path rule one owner in the gateoscabrielbefore adoptionf9808ff
lines 54–67why, one step back54const checkArgs = (check: StatedAsk["check"]) =>55 CheckSpec.match(decodeCheck(check), {56 LintToZero: ({ command, rule }): KindArgs => ({ command, rule }),57 Migrate: ({ count, from, to }): KindArgs => ({ count, from, to }),58 Ratchet: ({ ratchet }): KindArgs => ({ ratchet }),59 RedThenGreen: ({ path }): KindArgs => ({ path }),60 SymbolAbsent: ({ count, symbol }): KindArgs => ({ count, from: symbol }),61 });6263const territoryOf = ({ module, paths }: StatedAsk["territory"]) =>64 module === "."65 ? `territory.paths(${paths.map(spelled).join(", ")})`66 : `{ module: ${spelled(module)}, paths: ${spelled(paths)} }`;67Merge build/1205-dev-fixturesoscabrielbefore adoptionc816189
line 68why, one step back68export const askFileOf = (stated: StatedAsk): AskFile => {Tell stage 1 a pusher reads the layers only when they read every one, and give the no-oracle path rule one owner in the gateoscabrielbefore adoptionf9808ff
lines 69–103why, one step back69 const territory = territoryOf(stated.territory);7071 const passed = Object.entries({72 ...checkArgs(stated.check),73 blockedBy: Array.isReadonlyArrayNonEmpty(stated.blockedBy)74 ? stated.blockedBy75 : undefined,76 current: stated.brief.current,77 mentor: stated.mentor,78 parent: stated.parent,79 reserve: stated.reserve,80 want: stated.brief.want,81 }).flatMap(([key, value]) =>82 value === undefined ? [] : [`${key}: ${spelled(value)}`]83 );8485 const args = [...passed, `territory: ${territory}`].toSorted();8687 const builders = territory.startsWith("territory.")88 ? "kinds, territory"89 : "kinds";9091 return {92 content: [93 `import { ${builders} } from "${Brand.cliPackage}/rules";`,94 "",95 `export default kinds.${stated.kind}.ask({`,96 ...args.map((arg) => ` ${arg},`),97 "});",98 "",99 ].join("\n"),100 path: RepoPath.make(stated.file),101 };102};103Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
lines 104–105why, one step back104export const operator = Handle.make("oscabriel");105Tell stage 1 a pusher reads the layers only when they read every one, and give the no-oracle path rule one owner in the gateoscabrielbefore adoptionf9808ff
lines 106–344why, one step back106export const datekitPeople = {107 contributor: Handle.make("bram"),108 decider: Handle.make("ines-v"),109 zones: Handle.make("okonkwo"),110} as const;111112const fix = {113 checkKind: "redThenGreen",114 claimers: "vouched",115 finish: "optional",116 name: "fix",117 oneWay: false,118 race: 1,119 requires: ["want", "check", "territory"],120 strength: "assertion",121} satisfies typeof AskKind.Encoded;122123interface DatekitAsk {124 readonly stated: StatedAsk;125 readonly test: AskFile;126}127128const datekitAsk = (input: {129 readonly id: string;130 readonly file: string;131 readonly current: string;132 readonly want: string;133 readonly mentor?: Handle;134 readonly test: {135 readonly imports: readonly string[];136 readonly name: string;137 readonly assertion: string;138 };139}): DatekitAsk => {140 const path = RepoPath.make(`test/asks/${input.id}.test.ts`);141142 const stated: StatedAsk = {143 askedBy: datekitPeople.decider,144 blockedBy: [],145 brief: { current: input.current, want: input.want },146 check: encodeCheck(CheckSpec.cases.RedThenGreen.make({ path })),147 file: `${dir}/asks/${input.id}.ask.ts`,148 id: input.id,149 kind: "fix",150 territory: { module: ".", paths: [`src/${input.file}.ts`] },151 };152153 return {154 stated:155 input.mentor === undefined156 ? stated157 : { ...stated, mentor: input.mentor, reserve: "newcomers" },158 test: {159 content: [160 'import { expect, test } from "bun:test";',161 "",162 ...input.test.imports,163 "",164 `test(${spelled(input.test.name)}, () => {`,165 ` ${input.test.assertion}`,166 "});",167 "",168 ].join("\n"),169 path,170 },171 };172};173174const datekitAsks: readonly DatekitAsk[] = [175 datekitAsk({176 current: "parseISO returns an invalid date for a week date.",177 file: "parse",178 id: "parse-iso-week",179 test: {180 assertion:181 'expect(parseISO("2026-W41-3").toISOString()).toBe("2026-10-07T00:00:00.000Z");',182 imports: ['import { parseISO } from "../../src/parse.ts";'],183 name: "parses an ISO week date",184 },185 want: "parseISO accepts ISO week dates such as 2026-W41-3.",186 }),187 datekitAsk({188 current: 'format prints "11st", "12nd" and "13rd".',189 file: "format",190 id: "format-ordinal",191 mentor: datekitPeople.decider,192 test: {193 assertion: 'expect(format(parseISO("2026-10-11"), "Do")).toBe("11th");',194 imports: [195 'import { format } from "../../src/format.ts";',196 'import { parseISO } from "../../src/parse.ts";',197 ],198 name: "prints the teens as th",199 },200 want: 'format(date, "Do") prints 1st, 2nd, 3rd, 11th, 12th, 13th and 21st.',201 }),202 datekitAsk({203 current: "addMonths(January 31, 1) overflows into March.",204 file: "add",205 id: "add-months-clamp",206 test: {207 assertion:208 'expect(addMonths(parseISO("2026-01-31"), 1).toISOString()).toBe("2026-02-28T00:00:00.000Z");',209 imports: [210 'import { addMonths } from "../../src/add.ts";',211 'import { parseISO } from "../../src/parse.ts";',212 ],213 name: "clamps to the end of February",214 },215 want: "addMonths(January 31, 1) is the last day of February, in leap and common years.",216 }),217 datekitAsk({218 current: "diffInDays counts a day short across the spring change.",219 file: "diff",220 id: "diff-in-days-dst",221 test: {222 assertion:223 'expect(diffInDays(new Date("2026-03-30T00:00:00+02:00"), new Date("2026-03-29T00:00:00+01:00"))).toBe(1);',224 imports: ['import { diffInDays } from "../../src/diff.ts";'],225 name: "counts the spring change as one day",226 },227 want: "diffInDays counts calendar days across a daylight-saving change.",228 }),229];230231const library: Files = new Map([232 [233 "README.md",234 [235 "# datekit",236 "",237 "Small, dependency-free date helpers: parse, format, add and diff.",238 "",239 "A fictional project: it and its people are invented.",240 "",241 ].join("\n"),242 ],243 [244 "package.json",245 `${JSON.stringify(246 {247 license: "MIT",248 name: "datekit",249 scripts: { test: "bun test", typecheck: "tsc --noEmit" },250 type: "module",251 version: "0.4.2",252 },253 null,254 2255 )}\n`,256 ],257 [258 "src/index.ts",259 [260 'export { addMonths } from "./add.ts";',261 'export { diffInDays } from "./diff.ts";',262 'export { format } from "./format.ts";',263 'export { parseISO } from "./parse.ts";',264 'export { inZone } from "./tz.ts";',265 "",266 ].join("\n"),267 ],268 [269 "src/parse.ts",270 [271 "/** An ISO 8601 date (`2026-10-07`) or date-time, read as UTC. */",272 "export const parseISO = (text: string): Date =>",273 ' new Date(text.length === 10 ? text + "T00:00:00Z" : text);',274 "",275 ].join("\n"),276 ],277 [278 "src/format.ts",279 [280 'const pad = (n: number) => String(n).padStart(2, "0");',281 "",282 'const ordinal = (n: number) => String(n) + (["th", "st", "nd", "rd"][n % 10] ?? "th");',283 "",284 "/** `date` in `pattern`: YYYY, MM, DD and Do (the day as an ordinal). */",285 "export const format = (date: Date, pattern: string): string =>",286 " pattern",287 ' .replaceAll("YYYY", String(date.getUTCFullYear()))',288 ' .replaceAll("MM", pad(date.getUTCMonth() + 1))',289 ' .replaceAll("Do", ordinal(date.getUTCDate()))',290 ' .replaceAll("DD", pad(date.getUTCDate()));',291 "",292 ].join("\n"),293 ],294 [295 "src/add.ts",296 [297 "/** `date` moved by whole months. */",298 "export const addMonths = (date: Date, months: number): Date => {",299 " const next = new Date(date);",300 "",301 " next.setUTCMonth(next.getUTCMonth() + months);",302 "",303 " return next;",304 "};",305 "",306 ].join("\n"),307 ],308 [309 "src/diff.ts",310 [311 "const DAY = 86_400_000;",312 "",313 "/** Whole days from `earlier` to `later`. */",314 "export const diffInDays = (later: Date, earlier: Date): number =>",315 " Math.floor((later.getTime() - earlier.getTime()) / DAY);",316 "",317 ].join("\n"),318 ],319 [320 "src/tz.ts",321 [322 "/** `date` as wall-clock parts in an IANA time zone. */",323 "export const inZone = (date: Date, zone: string) =>",324 ' new Intl.DateTimeFormat("en-CA", { dateStyle: "short", timeStyle: "short", timeZone: zone }).format(date);',325 "",326 ].join("\n"),327 ],328 [329 "test/format.test.ts",330 [331 'import { expect, test } from "bun:test";',332 "",333 'import { format } from "../src/format.ts";',334 'import { parseISO } from "../src/parse.ts";',335 "",336 'test("formats a date", () => {',337 ' expect(format(parseISO("2026-10-07"), "YYYY-MM-DD")).toBe("2026-10-07");',338 "});",339 "",340 ].join("\n"),341 ],342 [343 `${dir}/policy.json`,344 policyJson({Merge project/drop-proposals into mainoscabrielbefore adoptionb4ed08b
line 345why, one step back345 asks: datekitAsks.map(({ stated }) => stated),Tell stage 1 a pusher reads the layers only when they read every one, and give the no-oracle path rule one owner in the gateoscabrielbefore adoptionf9808ff
lines 346–349why, one step back346 deciders: [347 { handles: [datekitPeople.decider], paths: "**" },348 { handles: [datekitPeople.zones], paths: "src/tz.ts" },349 ],Merge project/drop-proposals into mainoscabrielbefore adoptionb4ed08b
line 350why, one step back350 functions: { admit: false },Tell stage 1 a pusher reads the layers only when they read every one, and give the no-oracle path rule one owner in the gateoscabrielbefore adoptionf9808ff
lines 351–363why, one step back351 kinds: [fix],352 ratchets: [],353 run: {354 checks: { types: "bun run typecheck" },355 test: "bun test {path}",356 },357 source: "config",358 weakening: { markers: [".skip(", ".only(", ".todo("] },359 }),360 ],361 [362 `${dir}/vouched.td`,363 [Merge build/maintainer-wording into mainoscabrielbefore adoption4c1a571
line 364why, one step back364 "# The people datekit's maintainers vouch for.",Tell stage 1 a pusher reads the layers only when they read every one, and give the no-oracle path rule one owner in the gateoscabrielbefore adoptionf9808ff
lines 365–393why, one step back365 datekitPeople.contributor,366 "",367 ].join("\n"),368 ],369]);370371export const datekit = {372 answer: {373 ask: AskId.make("diff-in-days-dst"),374 files: new Map([375 [376 "src/diff.ts",377 [378 "const DAY = 86_400_000;",379 "",380 "/** Whole calendar days from `earlier` to `later`, across any daylight-saving change. */",381 "export const diffInDays = (later: Date, earlier: Date): number =>",382 " Math.round((later.getTime() - earlier.getTime()) / DAY);",383 "",384 ].join("\n"),385 ],386 ]) satisfies Files,387 message: "Count calendar days across a daylight-saving change",388 },389 asks: datekitAsks.map(390 ({ stated, test }) =>391 [AskId.make(stated.id), [askFileOf(stated), test]] as const392 ),393 files: library,Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 394why, one step back394 project: ProjectName.make("oscabriel/datekit"),Merge web/tour-and-refused-round into mainoscabrielbefore adoptionc3dd8ec
lines 395–462why, one step back395 /**396 * Bram's two rounds on parse-iso-week: the first refused at Shape for a397 * path outside the ask's territory, the second still checking.398 */399 rounds: {400 ask: AskId.make("parse-iso-week"),401 first: {402 files: new Map([403 [404 "src/parse.ts",405 [406 "const WEEK = /^(?<year>\\d{4})-W(?<week>\\d{2})-(?<day>[1-7])$/u;",407 "",408 "/** An ISO 8601 date (`2026-10-07`), week date (`2026-W41-3`) or date-time, read as UTC. */",409 "export const parseISO = (text: string): Date => {",410 " const week = WEEK.exec(text);",411 "",412 " if (week === null) {",413 ' return new Date(text.length === 10 ? text + "T00:00:00Z" : text);',414 " }",415 "",416 " // The week's Monday, from the week holding 4 January, comes next.",417 " return new Date(Number.NaN);",418 "};",419 "",420 ].join("\n"),421 ],422 ]) satisfies Files,423 message: "Start on ISO week dates",424 },425 outside: RepoPath.make("README.md"),426 second: {427 files: new Map([428 [429 "src/parse.ts",430 [431 "const WEEK = /^(?<year>\\d{4})-W(?<week>\\d{2})-(?<day>[1-7])$/u;",432 "",433 "const DAY = 86_400_000;",434 "",435 "/** The Monday of ISO week 1: the week holding 4 January. */",436 "const firstMonday = (year: number) => {",437 " const fourth = Date.UTC(year, 0, 4);",438 " const weekday = new Date(fourth).getUTCDay() || 7;",439 "",440 " return fourth - (weekday - 1) * DAY;",441 "};",442 "",443 "/** An ISO 8601 date (`2026-10-07`), week date (`2026-W41-3`) or date-time, read as UTC. */",444 "export const parseISO = (text: string): Date => {",445 " const week = WEEK.exec(text)?.groups;",446 "",447 " if (week === undefined) {",448 ' return new Date(text.length === 10 ? text + "T00:00:00Z" : text);',449 " }",450 "",451 " return new Date(",452 " firstMonday(Number(week.year)) +",453 " ((Number(week.week) - 1) * 7 + Number(week.day) - 1) * DAY",454 " );",455 "};",456 "",457 ].join("\n"),458 ],459 ]) satisfies Files,460 message: "Parse ISO week dates",461 },462 },Tell stage 1 a pusher reads the layers only when they read every one, and give the no-oracle path rule one owner in the gateoscabrielbefore adoptionf9808ff
lines 463–620why, one step back463 stray: {464 files: new Map([465 [466 "README.md",467 [468 "# datekit",469 "",470 "Small, dependency-free date helpers: parse, format, add, diff and time zones.",471 "",472 "A fictional project: it and its people are invented.",473 "",474 ].join("\n"),475 ],476 ]) satisfies Files,477 message: "Mention time zones in the README",478 },479} as const;480481export const burrowPeople = {482 decider: Handle.make("okafor"),483 second: Handle.make("lin-h"),484} as const;485486const PACKAGES = [487 "kit",488 "auth",489 "billing",490 "catalog",491 "notify",492 "search",493] as const;494495const COUNT = "bun scripts/count-callers.ts legacyFetch --json";496497const migrateCheck = encodeCheck(498 CheckSpec.cases.Migrate.make({499 count: Command.make(COUNT),500 from: SymbolName.make("legacyFetch"),501 to: SymbolName.make("http.get"),502 })503);504505const PARENT = "drop-legacy-fetch";506507const burrowAsks: readonly StatedAsk[] = [508 {509 askedBy: burrowPeople.decider,510 blockedBy: [],511 brief: {512 want: "Replace every call to legacyFetch with http.get, then delete legacyFetch.",513 },514 check: migrateCheck,515 file: `${dir}/asks/${PARENT}.ask.ts`,516 id: PARENT,517 kind: "migrate",518 territory: {519 module: ".",520 paths: Array.map(PACKAGES, (pkg) => `packages/${pkg}/**`),521 },522 },523];524525const packageFiles = (pkg: string): readonly (readonly [string, string])[] => [526 [527 `packages/${pkg}/package.json`,528 `${JSON.stringify(529 {530 exports: { ".": "./src/index.ts" },531 name: `@burrow/${pkg}`,532 type: "module",533 },534 null,535 2536 )}\n`,537 ],538 [539 `packages/${pkg}/src/index.ts`,540 pkg === "kit"541 ? [542 "/** The old way to fetch: kept until nothing calls it. */",543 "export const legacyFetch = (url: string) => fetch(url).then((response) => response.json());",544 "",545 "export const http = { get: (url: string) => fetch(url).then((response) => response.json()) };",546 "",547 "let calls = 0;",548 "",549 'export const ping = () => legacyFetch("/kit/ping?n=" + String((calls += 1)));',550 "",551 ].join("\n")552 : [553 'import { legacyFetch } from "@burrow/kit";',554 "",555 "let cache: unknown;",556 "",557 `export const load = async () => (cache ??= await legacyFetch("/${pkg}"));`,558 "",559 ].join("\n"),560 ],561];562563const monorepo: Files = new Map([564 [565 "README.md",566 [567 "# burrow",568 "",569 "Six packages that share a kit, a lint setup and a debt counter.",570 "",571 "A fictional project: it and its people are invented.",572 "",573 ].join("\n"),574 ],575 [576 "package.json",577 `${JSON.stringify(578 {579 name: "burrow",580 private: true,581 scripts: { lint: "oxlint", test: "bun test" },582 workspaces: ["packages/*"],583 },584 null,585 2586 )}\n`,587 ],588 [589 "scripts/count-callers.ts",590 [591 "// Prints how many times each package calls a symbol, as JSON.",592 'import { Glob } from "bun";',593 "",594 "const [symbol] = Bun.argv.slice(2);",595 "const byModule: Record<string, number> = {};",596 "",597 'for await (const path of new Glob("packages/*/src/**/*.ts").scan()) {',598 ' const name = "@burrow/" + path.split("/")[1];',599 " const text = await Bun.file(path).text();",600 "",601 ' byModule[name] = (byModule[name] ?? 0) + (text.split(symbol + "(").length - 1);',602 "}",603 "",604 "const total = Object.values(byModule).reduce((sum, n) => sum + n, 0);",605 "",606 "console.log(JSON.stringify({ byModule, total }));",607 "",608 ].join("\n"),609 ],610 ...PACKAGES.flatMap(packageFiles),611 [612 `${dir}/policy.json`,613 policyJson({614 asks: burrowAsks,615 deciders: [616 {617 handles: [burrowPeople.decider, burrowPeople.second],618 paths: "**",619 },620 ],Merge project/drop-proposals into mainoscabrielbefore adoptionb4ed08b
line 621why, one step back621 functions: { admit: false },Tell stage 1 a pusher reads the layers only when they read every one, and give the no-oracle path rule one owner in the gateoscabrielbefore adoptionf9808ff
lines 622–649why, one step back622 kinds: [623 {624 checkKind: "migrate",625 claimers: "vouched",626 finish: "never",627 name: "migrate",628 oneWay: false,629 race: 1,630 requires: ["want", "check", "territory"],631 strength: "assertion",632 },633 ],634 ratchets: [635 {636 measure: encodeMeasure(637 RatchetMeasure.cases.Count.make({638 command: Command.make("bun run lint --format json"),639 rule: "burrow/no-module-level-mutable-state",640 })641 ),642 name: "mutable-state",643 },644 ],645 run: { checks: { lint: "bun run lint" }, test: "bun test {path}" },646 source: "config",647 weakening: { markers: [".skip(", ".only(", ".todo("] },648 }),649 ],Merge build/maintainer-wording into mainoscabrielbefore adoption4c1a571
line 650why, one step back650 [`${dir}/vouched.td`, "# The people burrow's maintainers vouch for.\n"],Tell stage 1 a pusher reads the layers only when they read every one, and give the no-oracle path rule one owner in the gateoscabrielbefore adoptionf9808ff
lines 651–657why, one step back651]);652653export const burrow = {654 asks: burrowAsks.map(655 (stated) => [AskId.make(stated.id), [askFileOf(stated)]] as const656 ),657 files: monorepo,Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 658why, one step back658 project: ProjectName.make("oscabriel/burrow"),Tell stage 1 a pusher reads the layers only when they read every one, and give the no-oracle path rule one owner in the gateoscabrielbefore adoptionf9808ff
lines 659–686why, one step back659} as const;660661const callsIn = (text: string, symbol: string) =>662 text.split(`${symbol}(`).length - 1;663664const burrowCallers = () => {665 const byModule = Object.fromEntries(666 PACKAGES.map((pkg) => [667 `@burrow/${pkg}`,668 Number.sumAll(669 [...monorepo].flatMap(([path, text]) =>670 path.startsWith(`packages/${pkg}/src/`)671 ? [callsIn(text, "legacyFetch")]672 : []673 )674 ),675 ])676 );677678 return JSON.stringify({679 byModule,680 total: Number.sumAll(Object.values(byModule)),681 });682};683684export const printedBy: ReadonlyMap<string, string> = new Map([685 [COUNT, burrowCallers()],686]);