getDeclarationInfo.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import {isTopLevelDeclaration} from "../parser/tokenizer";
  2. import {TokenType as tt} from "../parser/tokenizer/types";
  3. export const EMPTY_DECLARATION_INFO = {
  4. typeDeclarations: new Set(),
  5. valueDeclarations: new Set(),
  6. };
  7. /**
  8. * Get all top-level identifiers that should be preserved when exported in TypeScript.
  9. *
  10. * Examples:
  11. * - If an identifier is declared as `const x`, then `export {x}` should be preserved.
  12. * - If it's declared as `type x`, then `export {x}` should be removed.
  13. * - If it's declared as both `const x` and `type x`, then the export should be preserved.
  14. * - Classes and enums should be preserved (even though they also introduce types).
  15. * - Imported identifiers should be preserved since we don't have enough information to
  16. * rule them out. --isolatedModules disallows re-exports, which catches errors here.
  17. */
  18. export default function getDeclarationInfo(tokens) {
  19. const typeDeclarations = new Set();
  20. const valueDeclarations = new Set();
  21. for (let i = 0; i < tokens.tokens.length; i++) {
  22. const token = tokens.tokens[i];
  23. if (token.type === tt.name && isTopLevelDeclaration(token)) {
  24. if (token.isType) {
  25. typeDeclarations.add(tokens.identifierNameForToken(token));
  26. } else {
  27. valueDeclarations.add(tokens.identifierNameForToken(token));
  28. }
  29. }
  30. }
  31. return {typeDeclarations, valueDeclarations};
  32. }