dependencyExtractor.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true
  4. });
  5. exports.extractor = void 0;
  6. /**
  7. * Copyright (c) Meta Platforms, Inc. and affiliates.
  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. const NOT_A_DOT = '(?<!\\.\\s*)';
  13. const CAPTURE_STRING_LITERAL = pos => `([\`'"])([^'"\`]*?)(?:\\${pos})`;
  14. const WORD_SEPARATOR = '\\b';
  15. const LEFT_PARENTHESIS = '\\(';
  16. const RIGHT_PARENTHESIS = '\\)';
  17. const WHITESPACE = '\\s*';
  18. const OPTIONAL_COMMA = '(:?,\\s*)?';
  19. function createRegExp(parts, flags) {
  20. return new RegExp(parts.join(''), flags);
  21. }
  22. function alternatives(...parts) {
  23. return `(?:${parts.join('|')})`;
  24. }
  25. function functionCallStart(...names) {
  26. return [
  27. NOT_A_DOT,
  28. WORD_SEPARATOR,
  29. alternatives(...names),
  30. WHITESPACE,
  31. LEFT_PARENTHESIS,
  32. WHITESPACE
  33. ];
  34. }
  35. const BLOCK_COMMENT_RE = /\/\*[^]*?\*\//g;
  36. const LINE_COMMENT_RE = /\/\/.*/g;
  37. const REQUIRE_OR_DYNAMIC_IMPORT_RE = createRegExp(
  38. [
  39. ...functionCallStart('require', 'import'),
  40. CAPTURE_STRING_LITERAL(1),
  41. WHITESPACE,
  42. OPTIONAL_COMMA,
  43. RIGHT_PARENTHESIS
  44. ],
  45. 'g'
  46. );
  47. const IMPORT_OR_EXPORT_RE = createRegExp(
  48. [
  49. '\\b(?:import|export)\\s+(?!type(?:of)?\\s+)(?:[^\'"]+\\s+from\\s+)?',
  50. CAPTURE_STRING_LITERAL(1)
  51. ],
  52. 'g'
  53. );
  54. const JEST_EXTENSIONS_RE = createRegExp(
  55. [
  56. ...functionCallStart(
  57. 'jest\\s*\\.\\s*(?:requireActual|requireMock|genMockFromModule|createMockFromModule)'
  58. ),
  59. CAPTURE_STRING_LITERAL(1),
  60. WHITESPACE,
  61. OPTIONAL_COMMA,
  62. RIGHT_PARENTHESIS
  63. ],
  64. 'g'
  65. );
  66. const extractor = {
  67. extract(code) {
  68. const dependencies = new Set();
  69. const addDependency = (match, _, dep) => {
  70. dependencies.add(dep);
  71. return match;
  72. };
  73. code
  74. .replace(BLOCK_COMMENT_RE, '')
  75. .replace(LINE_COMMENT_RE, '')
  76. .replace(IMPORT_OR_EXPORT_RE, addDependency)
  77. .replace(REQUIRE_OR_DYNAMIC_IMPORT_RE, addDependency)
  78. .replace(JEST_EXTENSIONS_RE, addDependency);
  79. return dependencies;
  80. }
  81. };
  82. exports.extractor = extractor;