UNPKG

10.6 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, '__esModule', { value: true });
4
5var path = require('path');
6var estreeWalker = require('estree-walker');
7var mm = require('micromatch');
8
9function addExtension(filename, ext) {
10 if (ext === void 0) { ext = '.js'; }
11 if (!path.extname(filename))
12 filename += ext;
13 return filename;
14}
15
16var blockDeclarations = {
17 const: true,
18 let: true
19};
20var extractors = {
21 Literal: function (names, param) {
22 names.push(param.value);
23 },
24 Identifier: function (names, param) {
25 names.push(param.name);
26 },
27 ObjectPattern: function (names, param) {
28 param.properties.forEach(function (prop) {
29 if (prop.type === 'RestElement') {
30 extractors.RestElement(names, prop);
31 }
32 else {
33 extractors[(prop.value || prop.key).type](names, prop.value || prop.key);
34 }
35 });
36 },
37 ArrayPattern: function (names, param) {
38 param.elements.forEach(function (element) {
39 if (element)
40 extractors[element.type](names, element);
41 });
42 },
43 RestElement: function (names, param) {
44 extractors[param.argument.type](names, param.argument);
45 },
46 AssignmentPattern: function (names, param) {
47 return extractors[param.left.type](names, param.left);
48 }
49};
50function extractNames(param) {
51 var names = [];
52 extractors[param.type](names, param);
53 return names;
54}
55var Scope = /** @class */ (function () {
56 function Scope(options) {
57 if (options === void 0) { options = {}; }
58 var _this = this;
59 this.parent = options.parent;
60 this.isBlockScope = !!options.block;
61 this.declarations = Object.create(null);
62 if (options.params) {
63 options.params.forEach(function (param) {
64 extractNames(param).forEach(function (name) {
65 _this.declarations[name] = true;
66 });
67 });
68 }
69 }
70 Scope.prototype.addDeclaration = function (node, isBlockDeclaration, isVar) {
71 var _this = this;
72 if (!isBlockDeclaration && this.isBlockScope) {
73 // it's a `var` or function node, and this
74 // is a block scope, so we need to go up
75 this.parent.addDeclaration(node, isBlockDeclaration, isVar);
76 }
77 else if (node.id) {
78 extractNames(node.id).forEach(function (name) {
79 _this.declarations[name] = true;
80 });
81 }
82 };
83 Scope.prototype.contains = function (name) {
84 return this.declarations[name] || (this.parent ? this.parent.contains(name) : false);
85 };
86 return Scope;
87}());
88function attachScopes(ast, propertyName) {
89 if (propertyName === void 0) { propertyName = 'scope'; }
90 var scope = new Scope();
91 estreeWalker.walk(ast, {
92 enter: function (node, parent) {
93 // function foo () {...}
94 // class Foo {...}
95 if (/(Function|Class)Declaration/.test(node.type)) {
96 scope.addDeclaration(node, false, false);
97 }
98 // var foo = 1
99 if (node.type === 'VariableDeclaration') {
100 var kind = node.kind;
101 var isBlockDeclaration_1 = blockDeclarations[kind];
102 node.declarations.forEach(function (declaration) {
103 scope.addDeclaration(declaration, isBlockDeclaration_1, true);
104 });
105 }
106 var newScope;
107 // create new function scope
108 if (/Function/.test(node.type)) {
109 newScope = new Scope({
110 parent: scope,
111 block: false,
112 params: node.params
113 });
114 // named function expressions - the name is considered
115 // part of the function's scope
116 if (node.type === 'FunctionExpression' && node.id) {
117 newScope.addDeclaration(node, false, false);
118 }
119 }
120 // create new block scope
121 if (node.type === 'BlockStatement' && !/Function/.test(parent.type)) {
122 newScope = new Scope({
123 parent: scope,
124 block: true
125 });
126 }
127 // catch clause has its own block scope
128 if (node.type === 'CatchClause') {
129 newScope = new Scope({
130 parent: scope,
131 params: [node.param],
132 block: true
133 });
134 }
135 if (newScope) {
136 Object.defineProperty(node, propertyName, {
137 value: newScope,
138 configurable: true
139 });
140 scope = newScope;
141 }
142 },
143 leave: function (node) {
144 if (node[propertyName])
145 scope = scope.parent;
146 }
147 });
148 return scope;
149}
150
151function ensureArray(thing) {
152 if (Array.isArray(thing))
153 return thing;
154 if (thing == undefined)
155 return [];
156 return [thing];
157}
158
159function createFilter(include, exclude) {
160 var getMatcher = function (id) {
161 return isRegexp(id)
162 ? id
163 : {
164 test: mm.matcher(path.resolve(id)
165 .split(path.sep)
166 .join('/'))
167 };
168 };
169 var includeMatchers = ensureArray(include).map(getMatcher);
170 var excludeMatchers = ensureArray(exclude).map(getMatcher);
171 return function (id) {
172 if (typeof id !== 'string')
173 return false;
174 if (/\0/.test(id))
175 return false;
176 id = id.split(path.sep).join('/');
177 for (var i = 0; i < excludeMatchers.length; ++i) {
178 var matcher = excludeMatchers[i];
179 if (matcher.test(id))
180 return false;
181 }
182 for (var i = 0; i < includeMatchers.length; ++i) {
183 var matcher = includeMatchers[i];
184 if (matcher.test(id))
185 return true;
186 }
187 return !includeMatchers.length;
188 };
189}
190function isRegexp(val) {
191 return val instanceof RegExp;
192}
193
194var reservedWords = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public'.split(' ');
195var builtins = 'arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl'.split(' ');
196var blacklisted = Object.create(null);
197reservedWords.concat(builtins).forEach(function (word) { return (blacklisted[word] = true); });
198function makeLegalIdentifier(str) {
199 str = str.replace(/-(\w)/g, function (_, letter) { return letter.toUpperCase(); }).replace(/[^$_a-zA-Z0-9]/g, '_');
200 if (/\d/.test(str[0]) || blacklisted[str])
201 str = "_" + str;
202 return str;
203}
204
205function serializeArray(arr, indent, baseIndent) {
206 var output = '[';
207 var separator = indent ? '\n' + baseIndent + indent : '';
208 for (var i = 0; i < arr.length; i++) {
209 var key = arr[i];
210 output += "" + (i > 0 ? ',' : '') + separator + serialize(key, indent, baseIndent + indent);
211 }
212 return output + ((indent ? '\n' + baseIndent : '') + "]");
213}
214function serializeObject(obj, indent, baseIndent) {
215 var output = '{';
216 var separator = indent ? '\n' + baseIndent + indent : '';
217 var keys = Object.keys(obj);
218 for (var i = 0; i < keys.length; i++) {
219 var key = keys[i];
220 var stringKey = makeLegalIdentifier(key) === key ? key : JSON.stringify(key);
221 output += "" + (i > 0 ? ',' : '') + separator + stringKey + ":" + (indent ? ' ' : '') + serialize(obj[key], indent, baseIndent + indent);
222 }
223 return output + ((indent ? '\n' + baseIndent : '') + "}");
224}
225function serialize(obj, indent, baseIndent) {
226 if (obj === Infinity)
227 return 'Infinity';
228 if (obj instanceof Date)
229 return 'new Date(' + obj.getTime() + ')';
230 if (obj instanceof RegExp)
231 return obj.toString();
232 if (typeof obj === 'number' && isNaN(obj))
233 return 'NaN';
234 if (Array.isArray(obj))
235 return serializeArray(obj, indent, baseIndent);
236 if (obj === null)
237 return 'null';
238 if (typeof obj === 'object')
239 return serializeObject(obj, indent, baseIndent);
240 return JSON.stringify(obj);
241}
242// convert data object into separate named exports (and default)
243function dataToNamedExports(data, options) {
244 if (options === void 0) { options = {}; }
245 var t = options.compact ? '' : 'indent' in options ? options.indent : '\t';
246 var _ = options.compact ? '' : ' ';
247 var n = options.compact ? '' : '\n';
248 var declarationType = options.preferConst ? 'const' : 'var';
249 if (options.namedExports === false ||
250 typeof data !== 'object' ||
251 Array.isArray(data) ||
252 data === null)
253 return "export default" + _ + serialize(data, options.compact ? null : t, '') + ";";
254 var namedExportCode = '';
255 var defaultExportRows = [];
256 var dataKeys = Object.keys(data);
257 for (var i = 0; i < dataKeys.length; i++) {
258 var key = dataKeys[i];
259 if (key === makeLegalIdentifier(key)) {
260 if (options.objectShorthand)
261 defaultExportRows.push(key);
262 else
263 defaultExportRows.push(key + ":" + _ + key);
264 namedExportCode += "export " + declarationType + " " + key + _ + "=" + _ + serialize(data[key], options.compact ? null : t, '') + ";" + n;
265 }
266 else {
267 defaultExportRows.push(JSON.stringify(key) + ": " + serialize(data[key], options.compact ? null : t, ''));
268 }
269 }
270 return (namedExportCode + ("export default" + _ + "{" + n + t + defaultExportRows.join("," + n + t) + n + "};" + n));
271}
272
273exports.addExtension = addExtension;
274exports.attachScopes = attachScopes;
275exports.createFilter = createFilter;
276exports.makeLegalIdentifier = makeLegalIdentifier;
277exports.dataToEsm = dataToNamedExports;