extract_requires.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true
  4. });
  5. exports.default = extractRequires;
  6. /**
  7. * Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
  8. *
  9. * This source code is licensed under the MIT license found in the
  10. * LICENSE file in the root directory of this source tree.
  11. *
  12. *
  13. */
  14. const blockCommentRe = /\/\*[^]*?\*\//g;
  15. const lineCommentRe = /\/\/.*/g;
  16. const replacePatterns = {
  17. DYNAMIC_IMPORT_RE: /(?:^|[^.]\s*)(\bimport\s*?\(\s*?)([`'"])([^`'"]+)(\2\s*?\))/g,
  18. EXPORT_RE: /(\bexport\s+(?!type )(?:[^'"]+\s+from\s+)??)(['"])([^'"]+)(\2)/g,
  19. IMPORT_RE: /(\bimport\s+(?!type )(?:[^'"]+\s+from\s+)??)(['"])([^'"]+)(\2)/g,
  20. REQUIRE_EXTENSIONS_PATTERN: /(?:^|[^.]\s*)(\b(?:require\s*?\.\s*?(?:requireActual|requireMock)|jest\s*?\.\s*?(?:requireActual|requireMock|genMockFromModule))\s*?\(\s*?)([`'"])([^`'"]+)(\2\s*?\))/g,
  21. REQUIRE_RE: /(?:^|[^.]\s*)(\brequire\s*?\(\s*?)([`'"])([^`'"]+)(\2\s*?\))/g
  22. };
  23. function extractRequires(code) {
  24. const dependencies = new Set();
  25. const addDependency = (match, pre, quot, dep, post) => {
  26. dependencies.add(dep);
  27. return match;
  28. };
  29. code
  30. .replace(blockCommentRe, '')
  31. .replace(lineCommentRe, '')
  32. .replace(replacePatterns.EXPORT_RE, addDependency)
  33. .replace(replacePatterns.IMPORT_RE, addDependency)
  34. .replace(replacePatterns.REQUIRE_EXTENSIONS_PATTERN, addDependency)
  35. .replace(replacePatterns.REQUIRE_RE, addDependency)
  36. .replace(replacePatterns.DYNAMIC_IMPORT_RE, addDependency);
  37. return Array.from(dependencies);
  38. }