UNPKG

2.36 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, '__esModule', {
4 value: true
5});
6exports.extract = extract;
7
8var _isRegExpSupported = _interopRequireDefault(require('./isRegExpSupported'));
9
10function _interopRequireDefault(obj) {
11 return obj && obj.__esModule ? obj : {default: obj};
12}
13
14/**
15 * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
16 *
17 * This source code is licensed under the MIT license found in the
18 * LICENSE file in the root directory of this source tree.
19 */
20// Negative look behind is only supported in Node 9+
21const NOT_A_DOT = (0, _isRegExpSupported.default)('(?<!\\.\\s*)')
22 ? '(?<!\\.\\s*)'
23 : '(?:^|[^.]\\s*)';
24
25const CAPTURE_STRING_LITERAL = pos => `([\`'"])([^'"\`]*?)(?:\\${pos})`;
26
27const WORD_SEPARATOR = '\\b';
28const LEFT_PARENTHESIS = '\\(';
29const RIGHT_PARENTHESIS = '\\)';
30const WHITESPACE = '\\s*';
31const OPTIONAL_COMMA = '(:?,\\s*)?';
32
33function createRegExp(parts, flags) {
34 return new RegExp(parts.join(''), flags);
35}
36
37function alternatives(...parts) {
38 return `(?:${parts.join('|')})`;
39}
40
41function functionCallStart(...names) {
42 return [
43 NOT_A_DOT,
44 WORD_SEPARATOR,
45 alternatives(...names),
46 WHITESPACE,
47 LEFT_PARENTHESIS,
48 WHITESPACE
49 ];
50}
51
52const BLOCK_COMMENT_RE = /\/\*[^]*?\*\//g;
53const LINE_COMMENT_RE = /\/\/.*/g;
54const REQUIRE_OR_DYNAMIC_IMPORT_RE = createRegExp(
55 [
56 ...functionCallStart('require', 'import'),
57 CAPTURE_STRING_LITERAL(1),
58 WHITESPACE,
59 OPTIONAL_COMMA,
60 RIGHT_PARENTHESIS
61 ],
62 'g'
63);
64const IMPORT_OR_EXPORT_RE = createRegExp(
65 [
66 '\\b(?:import|export)\\s+(?!type(?:of)?\\s+)(?:[^\'"]+\\s+from\\s+)?',
67 CAPTURE_STRING_LITERAL(1)
68 ],
69 'g'
70);
71const JEST_EXTENSIONS_RE = createRegExp(
72 [
73 ...functionCallStart(
74 'jest\\s*\\.\\s*(?:requireActual|requireMock|genMockFromModule|createMockFromModule)'
75 ),
76 CAPTURE_STRING_LITERAL(1),
77 WHITESPACE,
78 OPTIONAL_COMMA,
79 RIGHT_PARENTHESIS
80 ],
81 'g'
82);
83
84function extract(code) {
85 const dependencies = new Set();
86
87 const addDependency = (match, _, dep) => {
88 dependencies.add(dep);
89 return match;
90 };
91
92 code
93 .replace(BLOCK_COMMENT_RE, '')
94 .replace(LINE_COMMENT_RE, '')
95 .replace(IMPORT_OR_EXPORT_RE, addDependency)
96 .replace(REQUIRE_OR_DYNAMIC_IMPORT_RE, addDependency)
97 .replace(JEST_EXTENSIONS_RE, addDependency);
98 return dependencies;
99}