directivePieces

tcmts.core.extract.directivePieces · #pqnl7h6f · term · runs anywhere

// @ts-expect-error / // @ts-ignore comments directly above a declaration, as source pieces. They're kept with the definition (they decide whether it typechecks; like other comments they aren't hashed).

import type { Piece } from "#codebase/tcmts/core/extract";
import { getLeadingCommentRanges as ts_getLeadingCommentRanges, SyntaxKind as ts_SyntaxKind } from "typescript/ast";
import type { Node as ts_Node, SourceFile as ts_SourceFile } from "typescript/ast";

export function directivePieces(node: ts_Node, sf: ts_SourceFile): Piece[] {
  // the line comments directly above it; a directive's explanation may continue over several of them
  const comments = ts_getLeadingCommentRanges(sf.text, node.pos) ?? [];
  let first = comments.length;
  while (first > 0 && comments[first - 1]!.kind === ts_SyntaxKind.SingleLineCommentTrivia) first--;
  const run = comments.slice(first);
  const at = run.findIndex((c) => /^\/\/\/?\s*@ts-(expect-error|ignore)\b/.test(sf.text.slice(c.pos, c.end)));
  return at < 0 ? [] : run.slice(at).flatMap((c) => [{ start: c.pos, end: c.end }, { text: "\n" }]);
}

uses

used by