Skip to content
Myr

null-answer.ts

This file

Path

packages/checks/src/null-answer.ts

532 lines · 14.4 KiB · TypeScript

Last changed by

Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f

History of this file

Take it

1// ts-morph bundles the TypeScript compiler: only Bun hosts import this module, never a Worker.2import { WeakCheck } from "@repo/protocol/refusal";3import { Array, Effect, Option, pipe, Predicate, Result, Schema } from "effect";4import { Node, Project, ts } from "ts-morph";5import type { ImportDeclaration, SourceFile } from "ts-morph";67import { diagnose, Diagnosis } from "./classify.ts";8import type { RepoFile } from "./finder.ts";9import { matchGlob } from "./judge.ts";10import type { RunEvidence } from "./red-first.ts";1112export class NullAnswerFailed extends Schema.TaggedError<NullAnswerFailed>()(13  "NullAnswerFailed",14  { path: Schema.String, reason: Schema.String }15) {}1617export interface NullAnswerTerritory {18  readonly paths: readonly string[];19  readonly publicFiles?: readonly string[];20}2122interface Edit {23  readonly end: number;24  readonly start: number;25  readonly text: string;26}2728const NULL_BODY = "{ return undefined as never; }";2930const NULL_EXPRESSION = "undefined as never";3132const SOURCE = /\.(?:[cm]?ts|tsx)$/u;3334const DECLARATION = /\.d\.[cm]?ts$/u;3536const isSource = (path: string) => SOURCE.test(path) && !DECLARATION.test(path);3738const EXCLUDE = "!";3940const inTerritory = (territory: NullAnswerTerritory, path: string) =>41  territory.paths.some(42    (glob) => !glob.startsWith(EXCLUDE) && matchGlob(glob, path)43  ) &&44  !territory.paths.some(45    (glob) =>46      glob.startsWith(EXCLUDE) && matchGlob(glob.slice(EXCLUDE.length), path)47  );4849const ROOT = "/";5051const placed = (path: string) => `${ROOT}${path}`;5253const repoPathOf = (file: SourceFile) => file.getFilePath().slice(ROOT.length);5455const COMPILER_OPTIONS: ts.CompilerOptions = {56  allowImportingTsExtensions: true,57  module: ts.ModuleKind.Preserve,58  moduleResolution: ts.ModuleResolutionKind.Bundler,59  noEmit: true,60  target: ts.ScriptTarget.ES2023,61};6263const Manifest = Schema.fromJsonString(64  Schema.Struct({65    exports: Schema.optionalKey(Schema.Json),66    main: Schema.optionalKey(Schema.Json),67  })68);6970const decodeManifest = Schema.decodeUnknownOption(Manifest);7172const isJsonArray = (value: Schema.Json): value is Schema.JsonArray =>73  globalThis.Array.isArray(value);7475const isJsonObject = (value: Schema.Json): value is Schema.JsonObject =>76  Predicate.isObject(value) && !isJsonArray(value);7778const exportTargets = (value: Schema.Json | undefined): readonly string[] => {79  if (value === undefined || value === null) {80    return [];81  }8283  if (Predicate.isString(value)) {84    return [value];85  }8687  if (isJsonArray(value)) {88    return value.flatMap(exportTargets);89  }9091  return isJsonObject(value) ? Object.values(value).flatMap(exportTargets) : [];92};9394const targetsOf = ({95  exports,96  main,97}: typeof Manifest.Type): readonly string[] =>98  exports === undefined99    ? [main].filter(Predicate.isString)100    : exportTargets(exports);101102const PATTERN = "*";103104const targetPaths = (105  target: string,106  paths: readonly string[]107): readonly string[] => {108  const star = target.indexOf(PATTERN);109110  if (star === -1) {111    return [target];112  }113114  const head = target.slice(0, star);115  const tail = target.slice(star + PATTERN.length);116117  return paths.filter(118    (path) =>119      path.length > head.length + tail.length &&120      path.startsWith(head) &&121      path.endsWith(tail)122  );123};124125const folderOf = (path: string) => {126  const slash = path.lastIndexOf("/");127128  return slash === -1 ? "" : path.slice(0, slash);129};130131const joined = (folder: string, path: string) =>132  folder === "" ? path : `${folder}/${path}`;133134const foldersAbove = (path: string): readonly string[] => {135  const folders: string[] = [];136  let folder = folderOf(path);137138  while (folder !== "") {139    folders.push(folder);140    folder = folderOf(folder);141  }142143  return [...folders, ""];144};145146const manifestEntries = (147  files: readonly RepoFile[],148  territory: NullAnswerTerritory149): readonly string[] => {150  const texts = new Map(files.map(({ content, path }) => [path, content]));151  const paths = [...texts.keys()];152153  const manifests = pipe(154    files,155    Array.filter(({ path }) => inTerritory(territory, path)),156    Array.flatMap(({ path }) =>157      Option.toArray(158        Array.findFirst(foldersAbove(path), (folder) =>159          texts.has(joined(folder, "package.json"))160        )161      )162    ),163    Array.dedupe164  );165166  return pipe(167    manifests,168    Array.flatMap((folder) =>169      pipe(170        Option.fromUndefinedOr(texts.get(joined(folder, "package.json"))),171        Option.flatMap(decodeManifest),172        Option.match({173          onNone: () => [],174          onSome: (manifest) =>175            targetsOf(manifest).flatMap((target) =>176              targetPaths(177                joined(folder, target.replace(/^(?:\.\/)+/u, "")),178                paths179              )180            ),181        })182      )183    ),184    Array.filter((path) => texts.has(path) && isSource(path)),185    Array.dedupe186  );187};188189const bodyEdit = (body: Node | undefined): readonly Edit[] => {190  if (body === undefined) {191    return [];192  }193194  return [195    {196      end: body.getEnd(),197      start: body.getStart(),198      text: Node.isBlock(body) ? NULL_BODY : NULL_EXPRESSION,199    },200  ];201};202203const unwrapped = (node: Node): Node =>204  Node.isParenthesizedExpression(node) ||205  Node.isAsExpression(node) ||206  Node.isSatisfiesExpression(node)207    ? unwrapped(node.getExpression())208    : node;209210const stubsOf = (node: Node): readonly Edit[] => {211  if (212    Node.isFunctionDeclaration(node) ||213    Node.isFunctionExpression(node) ||214    Node.isArrowFunction(node)215  ) {216    return bodyEdit(node.getBody());217  }218219  if (Node.isVariableDeclaration(node) || Node.isPropertyDeclaration(node)) {220    const value = node.getInitializer();221222    return value === undefined ? [] : stubsOf(unwrapped(value));223  }224225  if (Node.isExportAssignment(node)) {226    return stubsOf(unwrapped(node.getExpression()));227  }228229  if (Node.isClassDeclaration(node) || Node.isClassExpression(node)) {230    return node231      .getMembers()232      .flatMap((member) =>233        Node.isMethodDeclaration(member) ||234        Node.isGetAccessorDeclaration(member)235          ? bodyEdit(member.getBody())236          : stubsOf(member)237      );238  }239240  return [];241};242243const edited = (text: string, edits: readonly Edit[]) => {244  const lastFirst = Array.dedupeWith(245    edits,246    (left, right) => left.start === right.start247  ).toSorted((left, right) => right.start - left.start);248249  let result = text;250251  for (const { end, start, text: replacement } of lastFirst) {252    result = `${result.slice(0, start)}${replacement}${result.slice(end)}`;253  }254255  return result;256};257258const ownExports = (file: SourceFile): readonly Node[] =>259  [...file.getExportedDeclarations().values()]260    .flat()261    .filter((node) => node.getSourceFile() === file);262263const IDENTIFIER = /^[A-Za-z_$][\w$]*$/u;264265const DEFAULT = "default";266267const standIn = (name: string) =>268  `export ${name === DEFAULT ? "default function " : `function ${name}`}(..._args: readonly unknown[]): never ${NULL_BODY}`;269270const withStandIns = (text: string, names: readonly string[]) => {271  const lines = names.map(standIn).join("\n");272273  if (text === "") {274    return `${lines}\n`;275  }276277  return `${text.endsWith("\n") ? text : `${text}\n`}\n${lines}\n`;278};279280// What a missing file's import is written as: a script's extension read as281// its TypeScript one, as Bun and `moduleResolution: "bundler"` read it.282const SCRIPT_AS_SOURCE = [283  [/\.js$/u, ".ts"],284  [/\.jsx$/u, ".tsx"],285  [/\.mjs$/u, ".mts"],286  [/\.cjs$/u, ".cts"],287] as const;288289const intendedPath = (importer: string, specifier: string) => {290  const segments: string[] = [];291292  for (const segment of [293    ...folderOf(importer).split("/"),294    ...specifier.split("/"),295  ]) {296    if (segment === "..") {297      segments.pop();298    } else if (segment !== "." && segment !== "") {299      segments.push(segment);300    }301  }302303  const path = segments.join("/");304305  const script = SCRIPT_AS_SOURCE.find(([extension]) => extension.test(path));306307  if (script !== undefined) {308    return path.replace(script[0], script[1]);309  }310311  return SOURCE.test(path) ? path : `${path}.ts`;312};313314const valueNamesOf = (declaration: ImportDeclaration): readonly string[] =>315  declaration.isTypeOnly()316    ? []317    : [318        ...(declaration.getDefaultImport() === undefined ? [] : [DEFAULT]),319        ...declaration320          .getNamedImports()321          .filter((specifier) => !specifier.isTypeOnly())322          .map((specifier) => specifier.getName())323          .filter((name) => IDENTIFIER.test(name)),324      ];325326const homeOf = (327  territory: NullAnswerTerritory,328  target: SourceFile329): Option.Option<SourceFile> =>330  inTerritory(territory, repoPathOf(target))331    ? Option.some(target)332    : Array.findFirst(target.getExportDeclarations(), (declaration) =>333        Option.fromUndefinedOr(334          declaration.hasNamedExports() || declaration.isNamespaceExport()335            ? undefined336            : declaration.getModuleSpecifierSourceFile()337        ).pipe(338          Option.filter((file) => inTerritory(territory, repoPathOf(file)))339        )340      );341342const wantedNames = (343  project: Project,344  territory: NullAnswerTerritory345): ReadonlyMap<string, readonly string[]> => {346  const wanted = new Map<string, string[]>();347348  const want = (path: string, names: readonly string[]) => {349    const known = wanted.get(path) ?? [];350351    wanted.set(path, Array.dedupe([...known, ...names]));352  };353354  for (const importer of project.getSourceFiles()) {355    for (const declaration of importer.getImportDeclarations()) {356      const specifier = declaration.getModuleSpecifierValue();357      const names = valueNamesOf(declaration);358      const target = declaration.getModuleSpecifierSourceFile();359360      if (specifier.startsWith(".") && Array.isReadonlyArrayNonEmpty(names)) {361        if (target === undefined) {362          const path = intendedPath(repoPathOf(importer), specifier);363364          if (inTerritory(territory, path)) {365            want(path, names);366          }367        } else {368          const exported = target.getExportedDeclarations();369370          for (const home of Option.toArray(homeOf(territory, target))) {371            const direct = home === target;372373            want(374              repoPathOf(home),375              names.filter((name) =>376                name === DEFAULT377                  ? direct && !exported.has(name)378                  : !exported.has(name) && home.getLocal(name) === undefined379              )380            );381          }382        }383      }384    }385  }386387  return new Map([...wanted].filter(([, names]) => names.length > 0));388};389390const messageOf = (cause: unknown) =>391  cause instanceof Error ? cause.message : globalThis.String(cause);392393const stubbedContents = (394  files: readonly RepoFile[],395  territory: NullAnswerTerritory,396  entryPaths: readonly string[]397): Result.Result<ReadonlyMap<string, string>, NullAnswerFailed> => {398  const project = new Project({399    compilerOptions: COMPILER_OPTIONS,400    skipFileDependencyResolution: true,401    skipLoadingLibFiles: true,402    useInMemoryFileSystem: true,403  });404405  for (const { content, path } of files) {406    if (isSource(path)) {407      project.createSourceFile(placed(path), content);408    }409  }410411  const entries = Array.getSomes(412    entryPaths.map((path) =>413      Option.fromUndefinedOr(project.getSourceFile(placed(path)))414    )415  );416417  // A set by reference: Effect's structural `dedupe` would walk each418  // ts-morph node's whole program.419  const reached = [420    ...new Set(421      entries.flatMap((entry) => [422        entry,423        ...[...entry.getExportedDeclarations().values()]424          .flat()425          .map((node) => node.getSourceFile()),426      ])427    ),428  ].filter((file) => inTerritory(territory, repoPathOf(file)));429430  const program = project.getProgram();431  const contents = new Map<string, string>();432433  for (const file of reached) {434    const [broken] = program.getSyntacticDiagnostics(file);435436    if (broken !== undefined) {437      return Result.fail(438        new NullAnswerFailed({439          path: repoPathOf(file),440          reason: ts.flattenDiagnosticMessageText(441            broken.compilerObject.messageText,442            "\n"443          ),444        })445      );446    }447448    const edits = ownExports(file).flatMap(stubsOf);449450    if (Array.isReadonlyArrayNonEmpty(edits)) {451      contents.set(repoPathOf(file), edited(file.getFullText(), edits));452    }453  }454455  for (const [path, names] of wantedNames(project, territory)) {456    const text =457      contents.get(path) ??458      project.getSourceFile(placed(path))?.getFullText() ??459      "";460461    contents.set(path, withStandIns(text, names));462  }463464  return Result.succeed(contents);465};466467// The null answer has only to run: a project with `noUnusedLocals` or468// `noUnusedParameters` will flag the stubs' unread parameters.469export const nullAnswer = (470  files: readonly RepoFile[],471  territory: NullAnswerTerritory472): Effect.Effect<readonly RepoFile[], NullAnswerFailed> =>473  Effect.gen(function* () {474    const where = territory.paths.join(" ");475476    const entryPaths =477      territory.publicFiles ?? manifestEntries(files, territory);478479    if (!Array.isReadonlyArrayNonEmpty(entryPaths)) {480      return yield* new NullAnswerFailed({481        path: where,482        reason:483          "no entry point: the territory names no public files, and no package.json exports a source file for it",484      });485    }486487    const contents = yield* Effect.try({488      catch: (cause) =>489        new NullAnswerFailed({ path: where, reason: messageOf(cause) }),490      try: () => stubbedContents(files, territory, entryPaths),491    }).pipe(Effect.flatMap(Effect.fromResult));492493    if (contents.size === 0) {494      return yield* new NullAnswerFailed({495        path: where,496        reason:497          "nothing to stub: the entry points export no function, arrow or class from the territory",498      });499    }500501    const given = new Set(files.map(({ path }) => path));502503    const added = [...contents]504      .flatMap(([path, content]) =>505        given.has(path) ? [] : [{ content, path }]506      )507      .toSorted((left, right) =>508        left.path < right.path ? -1 : Number(left.path > right.path)509      );510511    return [512      ...files.map((file) =>513        pipe(514          Option.fromUndefinedOr(contents.get(file.path)),515          Option.match({516            onNone: () => file,517            onSome: (content) => ({ content, path: file.path }),518          })519        )520      ),521      ...added,522    ];523  });524525export const nullAnswerVerdict = (run: RunEvidence): Option.Option<WeakCheck> =>526  Diagnosis.$match(diagnose(run.exit), {527    Blocked: () => Option.none(),528    Failed: () => Option.none(),529    LoadError: () => Option.none(),530    NoTests: () => Option.some(new WeakCheck({ weakness: "no assertion" })),531    Passed: () => Option.some(new WeakCheck({ weakness: "nullAnswer" })),532  });