Skip to content
Myr

ids.ts

This file

Path

packages/protocol/src/ids.ts

491 lines · 14.3 KiB · TypeScript

Last changed by

Merge redesign into mainoscabrielbefore adoptioncaedd21

History of this file

Take it

1import { Option, Schema, SchemaGetter } from "effect";23import { legacyProjects } from "./legacy.ts";45// Lowercase words joined by single dashes: no `--`, which separates a fork's6// parts (`<project>--<ask>--<handle>`), and no leading or trailing dash.7const Words = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u;89const ConfigName = /^[a-z][a-zA-Z0-9-]*$/u;1011const GitId = /^[0-9a-f]{40}$/u;1213const Minted = /^[a-z]+-[0-9a-z]{6,26}$/u;1415// `me` and `layer` name working forks and layer repos; `open` and `flag` are16// subcommands of `<cli> ask <ask>`, which would shadow an ask so named.17const reservedAskIds = ["me", "layer", "open", "flag"] as const;1819const isReserved = (name: string) =>20  reservedAskIds.some((reserved) => reserved === name);2122export const AskId = Schema.String.pipe(23  Schema.check(24    Schema.isPattern(Words),25    Schema.makeFilter(26      (name: string) =>27        isReserved(name)28          ? `${name} is reserved for working forks, layers and the CLI's ask commands, so no ask takes it`29          : true,30      {31        expected: `an ask name other than ${reservedAskIds.join(" or ")}`,32        toCode: () => ({33          runtime: `Schema.makeFilter((name: string) => !${JSON.stringify(reservedAskIds)}.includes(name))`,34        }),35        toJsonSchema: () => ({ not: { enum: [...reservedAskIds] } }),36      }37    )38  ),39  Schema.brand("AskId")40);4142export type AskId = typeof AskId.Type;4344export const CommitSha = Schema.String.pipe(45  Schema.check(Schema.isPattern(GitId)),46  Schema.brand("CommitSha")47);4849export type CommitSha = typeof CommitSha.Type;5051/** A commit the platform itself landed. Rules are read only from one, never from a pushed commit. */52export const LandedSha = CommitSha.pipe(Schema.brand("LandedSha"));5354export type LandedSha = typeof LandedSha.Type;5556export const TreeSha = Schema.String.pipe(57  Schema.check(Schema.isPattern(GitId)),58  Schema.brand("TreeSha")59);6061export type TreeSha = typeof TreeSha.Type;6263export const BlobSha = Schema.String.pipe(64  Schema.check(Schema.isPattern(GitId)),65  Schema.brand("BlobSha")66);6768export type BlobSha = typeof BlobSha.Type;6970/** SHA-256 over the sorted (path, blob before, blob after) triples an answer changes. */71export const PatchId = Schema.String.pipe(72  Schema.check(Schema.isPattern(/^[0-9a-f]{64}$/u)),73  Schema.brand("PatchId")74);7576export type PatchId = typeof PatchId.Type;7778export const RequestId = Schema.String.pipe(79  Schema.check(Schema.isPattern(/^[A-Za-z0-9_-]{8,64}$/u)),80  Schema.brand("RequestId")81);8283export type RequestId = typeof RequestId.Type;8485/** Reserved: today the person's platform token is the credential. */86export const ClaimToken = Schema.RedactedFromValue(Schema.String);8788export type ClaimToken = typeof ClaimToken.Type;8990export const ProposalId = Schema.String.pipe(91  Schema.check(Schema.isPattern(Minted)),92  Schema.brand("ProposalId")93);9495export type ProposalId = typeof ProposalId.Type;9697export const DecisionId = Schema.String.pipe(98  Schema.check(Schema.isPattern(Minted)),99  Schema.brand("DecisionId")100);101102export type DecisionId = typeof DecisionId.Type;103104export const LandingId = Schema.String.pipe(105  Schema.check(Schema.isPattern(Minted)),106  Schema.brand("LandingId")107);108109export type LandingId = typeof LandingId.Type;110111export const KindName = Schema.String.pipe(112  Schema.check(Schema.isPattern(ConfigName)),113  Schema.brand("KindName")114);115116export type KindName = typeof KindName.Type;117118// Single hyphens only: its repo is `<project>--<layer>`, and a `--` in the119// name would read as a claim fork's.120export const LayerName = Schema.String.pipe(121  Schema.check(Schema.isPattern(Words)),122  Schema.brand("LayerName")123);124125export type LayerName = typeof LayerName.Type;126127export const AreaName = Schema.String.pipe(128  Schema.check(Schema.isPattern(ConfigName)),129  Schema.brand("AreaName")130);131132export type AreaName = typeof AreaName.Type;133134export const LaneName = Schema.String.pipe(135  Schema.check(Schema.isPattern(ConfigName)),136  Schema.brand("LaneName")137);138139export type LaneName = typeof LaneName.Type;140141export const RatchetName = Schema.String.pipe(142  Schema.check(Schema.isPattern(ConfigName)),143  Schema.brand("RatchetName")144);145146export type RatchetName = typeof RatchetName.Type;147148export const EnvKey = Schema.String.pipe(149  Schema.check(Schema.isPattern(/^[A-Za-z_][A-Za-z0-9_]*$/u)),150  Schema.brand("EnvKey")151);152153export type EnvKey = typeof EnvKey.Type;154155export const SuiteRoot = Schema.String.pipe(156  Schema.check(Schema.isPattern(/^sha256:[0-9a-f]{64}$/u)),157  Schema.brand("SuiteRoot")158);159160export type SuiteRoot = typeof SuiteRoot.Type;161162/** A verdict is reused only for the same tree and version: `redThenGreen@0.0.0+<hash>`. */163export const CheckVersion = Schema.NonEmptyString.pipe(164  Schema.brand("CheckVersion")165);166167export type CheckVersion = typeof CheckVersion.Type;168169export const RepoName = Schema.String.pipe(170  Schema.check(Schema.isPattern(/^[A-Za-z0-9._-]+$/u)),171  Schema.brand("RepoName")172);173174export type RepoName = typeof RepoName.Type;175176/** A branch by its short name: never `refs/...`, never `..`, no empty part. */177export const BranchName = Schema.String.pipe(178  Schema.check(179    Schema.isPattern(180      /^(?!refs\/)(?!.*\.\.)[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/u181    )182  ),183  Schema.brand("BranchName")184);185186export type BranchName = typeof BranchName.Type;187188export const RepoPath = Schema.NonEmptyString.pipe(Schema.brand("RepoPath"));189190export type RepoPath = typeof RepoPath.Type;191192// The web serves its own pages at these first path segments, so a project193// owned by one would be unreachable. `apps/web/test/routes.test.ts` holds194// this list to the web's routes and the few reserved ahead of their page.195export const reservedProjectNames = [196  "agents",197  "asks",198  "assets",199  "auth",200  "docs",201  "explore",202  "home",203  "icons",204  "import",205  "inbox",206  "install",207  "people",208  "privacy",209  "releases",210  "rpc",211  "settings",212  "terms",213  "today",214] as const;215216const isReservedOwner = (owner: string) =>217  reservedProjectNames.some((reserved) => reserved === owner);218219export const sourceHosts = [220  "github.com",221  "gitlab.com",222  "codeberg.org",223  "bitbucket.org",224] as const;225226export type SourceHost = (typeof sourceHosts)[number];227228const isSourceHost = (host: string): host is SourceHost =>229  sourceHosts.some((known) => known === host);230231// A segment of a project's name: lowercase letters and digits joined by232// single dots, dashes or underscores, so `--` never occurs (it separates a233// fork's parts) and the segment is safe to paste into a shell.234const SEGMENT = String.raw`[a-z0-9]+(?:[._-][a-z0-9]+)*`;235236// A handle as an owner: a lowercase handle with single dashes. A handle may237// not hold `_` or `.`, so it is never mistaken for a host.238const HANDLE_OWNER = String.raw`[a-z0-9]+(?:-[a-z0-9]+)*`;239240const HOSTS = sourceHosts.map((host) => host.replaceAll(".", "\\.")).join("|");241242const SourceNamespacePattern = new RegExp(243  String.raw`^(?:${HOSTS})/${SEGMENT}$`,244  "u"245);246247const OwnerPattern = new RegExp(248  String.raw`^(?:${HANDLE_OWNER}|(?:${HOSTS})/${SEGMENT})$`,249  "u"250);251252// A short name never ends as a file the web serves beside a page does253// (`llms.txt`, `<ask>.md`), so `/<owner>/llms.txt` is never a project.254const SHORT = String.raw`(?![^/]*\.(?:txt|md)$)${SEGMENT}`;255256const ShortNamePattern = new RegExp(String.raw`^${SHORT}$`, "u");257258const FullNamePattern = new RegExp(259  String.raw`^(?:${HANDLE_OWNER}|(?:${HOSTS})/${SEGMENT})/${SHORT}$`,260  "u"261);262263const SpelledPattern = /^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+){0,2}$/u;264265export const SourceNamespace = Schema.String.pipe(266  Schema.check(Schema.isPattern(SourceNamespacePattern)),267  Schema.brand("SourceNamespace")268);269270export type SourceNamespace = typeof SourceNamespace.Type;271272// A handle holds no dot and a host always does, so an owner is never both.273export const Owner = Schema.String.pipe(274  Schema.check(275    Schema.isPattern(OwnerPattern),276    Schema.makeFilter(277      (owner: string) =>278        isReservedOwner(owner)279          ? `${owner} is a path the web serves its own pages at, so no owner takes it`280          : true,281      {282        expected: `an owner other than ${reservedProjectNames.join(" or ")}`,283        toCode: () => ({284          runtime: `Schema.makeFilter((owner: string) => !${JSON.stringify(reservedProjectNames)}.includes(owner))`,285        }),286        toJsonSchema: () => ({ not: { enum: [...reservedProjectNames] } }),287      }288    )289  ),290  Schema.brand("Owner")291);292293export type Owner = typeof Owner.Type;294295export const isSourceNamespace = (296  owner: Owner297): owner is Owner & SourceNamespace => SourceNamespacePattern.test(owner);298299export const ShortName = Schema.String.pipe(300  Schema.check(Schema.isPattern(ShortNamePattern)),301  Schema.brand("ShortName")302);303304export type ShortName = typeof ShortName.Type;305306const FullName = Schema.String.pipe(307  Schema.check(308    Schema.isPattern(FullNamePattern),309    Schema.makeFilter(310      (name: string) => {311        const owner = name.slice(0, name.lastIndexOf("/"));312313        return isReservedOwner(owner)314          ? `${owner} is a path the web serves its own pages at, so no project is owned by it`315          : true;316      },317      {318        expected: `a project name whose owner is none of ${reservedProjectNames.join(", ")}`,319        toCode: () => ({320          runtime: `Schema.makeFilter((name: string) => !${JSON.stringify(reservedProjectNames)}.includes(name.slice(0, name.lastIndexOf("/"))))`,321        }),322      }323    )324  ),325  Schema.brand("ProjectName")326);327328// Each `/` becomes `__`. No segment holds two separators in a row, so a key329// reads back to its name even when segments hold `_`. Never `--`, which330// separates a fork's parts.331export const ProjectKey = Schema.String.pipe(332  Schema.check(Schema.isPattern(/^(?!.*--)[a-z0-9._-]+$/u)),333  Schema.brand("ProjectKey")334);335336export type ProjectKey = typeof ProjectKey.Type;337338const legacyNameByKey: Readonly<Record<string, string>> = Object.fromEntries(339  legacyProjects.map(({ key, name }) => [key, name])340);341342const legacyKeyByName: Readonly<Record<string, string>> = Object.fromEntries(343  legacyProjects.map(({ key, name }) => [name, key])344);345346const spelledToName = (spelled: string): string => {347  const lower = spelled.toLowerCase();348349  return lower.includes("/") ? lower : (legacyNameByKey[lower] ?? lower);350};351352// Decoding lowercases and reads a bare legacy key (`datekit`) as its full name,353// so stored events and old remotes still resolve. It encodes only the full name.354export const ProjectName = Schema.String.pipe(355  Schema.check(Schema.isPattern(SpelledPattern)),356  Schema.decodeTo(FullName, {357    decode: SchemaGetter.transform(spelledToName),358    encode: SchemaGetter.transform((name: string) => name),359  })360);361362export type ProjectName = typeof ProjectName.Type;363364export const ownerOf = (name: ProjectName): Owner =>365  Owner.make(name.slice(0, name.lastIndexOf("/")));366367export const shortNameOf = (name: ProjectName): ShortName =>368  ShortName.make(name.slice(name.lastIndexOf("/") + 1));369370export const projectNameOf = (owner: Owner, short: ShortName): ProjectName =>371  ProjectName.make(`${owner}/${short}`);372373export const keyOf = (name: ProjectName): ProjectKey =>374  ProjectKey.make(legacyKeyByName[name] ?? name.replaceAll("/", "__"));375376const decodeFullName = Schema.decodeOption(FullName);377378export const nameOfKey = (key: ProjectKey): Option.Option<ProjectName> => {379  const legacy = legacyNameByKey[key];380381  if (legacy !== undefined) {382    return Option.some(ProjectName.make(legacy));383  }384385  return key.includes("__")386    ? decodeFullName(key.replaceAll("__", "/"))387    : Option.none();388};389390const decodeName = Schema.decodeOption(ProjectName);391392const SOURCE_URL =393  /^https:\/\/(?<host>[^/?#]+)\/(?<account>[^/?#]+)\/(?<repo>[^/?#]+?)(?:\.git)?\/?$/u;394395export const ProjectNameFromKey = ProjectKey.pipe(396  Schema.decodeTo(FullName, {397    decode: SchemaGetter.transform((key: string) =>398      Option.getOrElse(nameOfKey(ProjectKey.make(key)), () => key)399    ),400    encode: SchemaGetter.transform((name: string) =>401      keyOf(ProjectName.make(name))402    ),403  })404);405406const forkPartsOf = (name: string) => {407  const dashes = name.indexOf("--");408409  return dashes === -1410    ? { head: name, suffix: "" }411    : { head: name.slice(0, dashes), suffix: name.slice(dashes) };412};413414export const repoNameOfAddress = (address: string): Option.Option<RepoName> => {415  const slash = address.lastIndexOf("/");416  const { head: short, suffix } = forkPartsOf(address.slice(slash + 1));417  const spelled = slash === -1 ? short : `${address.slice(0, slash)}/${short}`;418419  return Option.flatMap(decodeName(spelled), (name) =>420    Schema.decodeOption(RepoName)(`${keyOf(name)}${suffix}`)421  );422};423424export const addressOfRepo = (repo: RepoName): Option.Option<string> => {425  const { head: first, suffix } = forkPartsOf(repo);426427  return Option.map(428    Option.flatMap(Schema.decodeOption(ProjectKey)(first), nameOfKey),429    (name) => `${name}${suffix}`430  );431};432433export interface ProjectAddress {434  readonly spelled: string;435  readonly legacy: boolean;436  readonly rest: readonly string[];437}438439export const projectAddressOf = (440  segments: readonly string[]441): Option.Option<ProjectAddress> => {442  const first = segments[0]?.toLowerCase();443444  if (first === undefined) {445    return Option.none();446  }447448  const legacy = legacyNameByKey[first] !== undefined;449  const owned = isSourceHost(first) ? 3 : 2;450  const length = legacy ? 1 : owned;451452  return segments.length < length453    ? Option.none()454    : Option.some({455        legacy,456        rest: segments.slice(length),457        spelled: segments.slice(0, length).join("/"),458      });459};460461export const sourceNamespaceOf = (462  url: string463): Option.Option<SourceNamespace> => {464  // `https://<host>/<account>/<repo>(.git)(/)`, read without `URL`, which465  // not every host the protocol compiles on provides.466  const parts = SOURCE_URL.exec(url);467  const host = parts?.groups?.host?.toLowerCase();468  const account = parts?.groups?.account?.toLowerCase();469470  return host === undefined || account === undefined || !isSourceHost(host)471    ? Option.none()472    : Schema.decodeOption(SourceNamespace)(`${host}/${account}`);473};474475export const Handle = Schema.String.pipe(476  Schema.check(Schema.isPattern(/^[A-Za-z0-9][A-Za-z0-9-]*$/u)),477  Schema.brand("Handle")478);479480export type Handle = typeof Handle.Type;481482/** Handles compare without case, as accounts and claim forks do. Every package compares by this. */483export const sameHandle = (one: Handle, other: Handle): boolean =>484  one.toLowerCase() === other.toLowerCase();485486export const claimForkName = (487  project: ProjectName,488  ask: AskId,489  handle: Handle490): RepoName =>491  RepoName.make(`${keyOf(project)}--${ask}--${handle.toLowerCase()}`);