getImportExportSpecifierInfo.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _types = require('../parser/tokenizer/types');
  2. /**
  3. * Determine information about this named import or named export specifier.
  4. *
  5. * This syntax is the `a` from statements like these:
  6. * import {A} from "./foo";
  7. * export {A};
  8. * export {A} from "./foo";
  9. *
  10. * As it turns out, we can exactly characterize the syntax meaning by simply
  11. * counting the number of tokens, which can be from 1 to 4:
  12. * {A}
  13. * {type A}
  14. * {A as B}
  15. * {type A as B}
  16. *
  17. * In the type case, we never actually need the names in practice, so don't get
  18. * them.
  19. *
  20. * TODO: There's some redundancy with the type detection here and the isType
  21. * flag that's already present on tokens in TS mode. This function could
  22. * potentially be simplified and/or pushed to the call sites to avoid the object
  23. * allocation.
  24. */
  25. function getImportExportSpecifierInfo(
  26. tokens,
  27. index = tokens.currentIndex(),
  28. ) {
  29. let endIndex = index + 1;
  30. if (isSpecifierEnd(tokens, endIndex)) {
  31. // import {A}
  32. const name = tokens.identifierNameAtIndex(index);
  33. return {
  34. isType: false,
  35. leftName: name,
  36. rightName: name,
  37. endIndex,
  38. };
  39. }
  40. endIndex++;
  41. if (isSpecifierEnd(tokens, endIndex)) {
  42. // import {type A}
  43. return {
  44. isType: true,
  45. leftName: null,
  46. rightName: null,
  47. endIndex,
  48. };
  49. }
  50. endIndex++;
  51. if (isSpecifierEnd(tokens, endIndex)) {
  52. // import {A as B}
  53. return {
  54. isType: false,
  55. leftName: tokens.identifierNameAtIndex(index),
  56. rightName: tokens.identifierNameAtIndex(index + 2),
  57. endIndex,
  58. };
  59. }
  60. endIndex++;
  61. if (isSpecifierEnd(tokens, endIndex)) {
  62. // import {type A as B}
  63. return {
  64. isType: true,
  65. leftName: null,
  66. rightName: null,
  67. endIndex,
  68. };
  69. }
  70. throw new Error(`Unexpected import/export specifier at ${index}`);
  71. } exports.default = getImportExportSpecifierInfo;
  72. function isSpecifierEnd(tokens, index) {
  73. const token = tokens.tokens[index];
  74. return token.type === _types.TokenType.braceR || token.type === _types.TokenType.comma;
  75. }