unambiguous.js 921 B

123456789101112131415161718192021222324252627282930
  1. 'use strict';
  2. exports.__esModule = true;
  3. const pattern = /(^|;)\s*(export|import)((\s+\w)|(\s*[{*=]))|import\(/m;
  4. /**
  5. * detect possible imports/exports without a full parse.
  6. *
  7. * A negative test means that a file is definitely _not_ a module.
  8. * A positive test means it _could_ be.
  9. *
  10. * Not perfect, just a fast way to disqualify large non-ES6 modules and
  11. * avoid a parse.
  12. * @type {RegExp}
  13. */
  14. exports.test = function isMaybeUnambiguousModule(content) {
  15. return pattern.test(content);
  16. };
  17. // future-/Babel-proof at the expense of being a little loose
  18. const unambiguousNodeType = /^(?:(?:Exp|Imp)ort.*Declaration|TSExportAssignment)$/;
  19. /**
  20. * Given an AST, return true if the AST unambiguously represents a module.
  21. * @param {Program node} ast
  22. * @return {Boolean}
  23. */
  24. exports.isModule = function isUnambiguousModule(ast) {
  25. return ast.body && ast.body.some((node) => unambiguousNodeType.test(node.type));
  26. };