Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

JavaScript · 95 lines · 2.7 KiB · at 9472e3c

// The strictness checker. Runs on preprocessed (valid-TS) source of .tsus// files only; plain .ts dependencies are exempt by design.import ts from "typescript";const RULES = {  TSUS001: {    message: "class declarations are banned in .tsus files",    hint: "Use plain object types and functions.",  },  TSUS002: {    message: "null is banned in .tsus files",    hint: "Use Option<T> from @tsus/runtime, or fromNullable at the boundary.",  },  TSUS003: {    message: "undefined is banned in .tsus files",    hint: "Use Option<T> from @tsus/runtime, or fromNullable at the boundary.",  },  TSUS004: {    message: "var is banned in .tsus files",    hint: "Use const (preferred) or let.",  },  TSUS005: {    message: "throw is banned in .tsus files",    hint: "Return Result<T, E> from @tsus/runtime, or wrapSync/wrapAsync at the boundary.",  },};// `locate(offset)` maps an offset in `code` to a 1-based { line, col } in the// original .tsus file; without it, positions are reported in `code` itself.export const checkSource = (fileName, code, locate) => {  const sourceFile = ts.createSourceFile(    fileName,    code,    ts.ScriptTarget.ES2022,    true,    ts.ScriptKind.TS,  );  const diagnostics = [];  const where = (offset) => {    if (locate) {      return locate(offset);    }    const { line, character } = sourceFile.getLineAndCharacterOfPosition(offset);    return { line: line + 1, col: character + 1 };  };  const add = (node, code) => {    diagnostics.push({      code,      message: RULES[code].message,      hint: RULES[code].hint,      file: fileName,      ...where(node.getStart(sourceFile)),    });  };  const visit = (node) => {    if (ts.isClassDeclaration(node) || ts.isClassExpression(node)) {      add(node, "TSUS001");    }    if (node.kind === ts.SyntaxKind.NullKeyword) {      add(node, "TSUS002");    }    if (ts.isIdentifier(node) && node.text === "undefined") {      add(node, "TSUS003");    }    if (      ts.isVariableDeclarationList(node) &&      (node.flags & (ts.NodeFlags.Let | ts.NodeFlags.Const)) === 0    ) {      add(node, "TSUS004");    }    if (ts.isThrowStatement(node)) {      add(node, "TSUS005");    }    ts.forEachChild(node, visit);  };  visit(sourceFile);  const parseErrors = sourceFile.parseDiagnostics ?? [];  for (const d of parseErrors) {    diagnostics.push({      code: "TSUS000",      message: `syntax error: ${ts.flattenDiagnosticMessageText(d.messageText, " ")}`,      hint: "The file does not parse as TypeScript after macro expansion.",      tsCode: d.code,      file: fileName,      ...where(d.start ?? 0),    });  }  diagnostics.sort((a, b) => a.line - b.line || a.col - b.col);  return diagnostics;};