index.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. import { extname, sep, resolve, posix } from 'path';
  2. import pm from 'picomatch';
  3. const addExtension = function addExtension(filename, ext = '.js') {
  4. let result = `${filename}`;
  5. if (!extname(filename))
  6. result += ext;
  7. return result;
  8. };
  9. function walk(ast, { enter, leave }) {
  10. return visit(ast, null, enter, leave);
  11. }
  12. let should_skip = false;
  13. let should_remove = false;
  14. let replacement = null;
  15. const context = {
  16. skip: () => should_skip = true,
  17. remove: () => should_remove = true,
  18. replace: (node) => replacement = node
  19. };
  20. function replace(parent, prop, index, node) {
  21. if (parent) {
  22. if (index !== null) {
  23. parent[prop][index] = node;
  24. } else {
  25. parent[prop] = node;
  26. }
  27. }
  28. }
  29. function remove(parent, prop, index) {
  30. if (parent) {
  31. if (index !== null) {
  32. parent[prop].splice(index, 1);
  33. } else {
  34. delete parent[prop];
  35. }
  36. }
  37. }
  38. function visit(
  39. node,
  40. parent,
  41. enter,
  42. leave,
  43. prop,
  44. index
  45. ) {
  46. if (node) {
  47. if (enter) {
  48. const _should_skip = should_skip;
  49. const _should_remove = should_remove;
  50. const _replacement = replacement;
  51. should_skip = false;
  52. should_remove = false;
  53. replacement = null;
  54. enter.call(context, node, parent, prop, index);
  55. if (replacement) {
  56. node = replacement;
  57. replace(parent, prop, index, node);
  58. }
  59. if (should_remove) {
  60. remove(parent, prop, index);
  61. }
  62. const skipped = should_skip;
  63. const removed = should_remove;
  64. should_skip = _should_skip;
  65. should_remove = _should_remove;
  66. replacement = _replacement;
  67. if (skipped) return node;
  68. if (removed) return null;
  69. }
  70. for (const key in node) {
  71. const value = (node )[key];
  72. if (typeof value !== 'object') {
  73. continue;
  74. }
  75. else if (Array.isArray(value)) {
  76. for (let j = 0, k = 0; j < value.length; j += 1, k += 1) {
  77. if (value[j] !== null && typeof value[j].type === 'string') {
  78. if (!visit(value[j], node, enter, leave, key, k)) {
  79. // removed
  80. j--;
  81. }
  82. }
  83. }
  84. }
  85. else if (value !== null && typeof value.type === 'string') {
  86. visit(value, node, enter, leave, key, null);
  87. }
  88. }
  89. if (leave) {
  90. const _replacement = replacement;
  91. const _should_remove = should_remove;
  92. replacement = null;
  93. should_remove = false;
  94. leave.call(context, node, parent, prop, index);
  95. if (replacement) {
  96. node = replacement;
  97. replace(parent, prop, index, node);
  98. }
  99. if (should_remove) {
  100. remove(parent, prop, index);
  101. }
  102. const removed = should_remove;
  103. replacement = _replacement;
  104. should_remove = _should_remove;
  105. if (removed) return null;
  106. }
  107. }
  108. return node;
  109. }
  110. const extractors = {
  111. ArrayPattern(names, param) {
  112. for (const element of param.elements) {
  113. if (element)
  114. extractors[element.type](names, element);
  115. }
  116. },
  117. AssignmentPattern(names, param) {
  118. extractors[param.left.type](names, param.left);
  119. },
  120. Identifier(names, param) {
  121. names.push(param.name);
  122. },
  123. MemberExpression() { },
  124. ObjectPattern(names, param) {
  125. for (const prop of param.properties) {
  126. // @ts-ignore Typescript reports that this is not a valid type
  127. if (prop.type === 'RestElement') {
  128. extractors.RestElement(names, prop);
  129. }
  130. else {
  131. extractors[prop.value.type](names, prop.value);
  132. }
  133. }
  134. },
  135. RestElement(names, param) {
  136. extractors[param.argument.type](names, param.argument);
  137. }
  138. };
  139. const extractAssignedNames = function extractAssignedNames(param) {
  140. const names = [];
  141. extractors[param.type](names, param);
  142. return names;
  143. };
  144. const blockDeclarations = {
  145. const: true,
  146. let: true
  147. };
  148. class Scope {
  149. constructor(options = {}) {
  150. this.parent = options.parent;
  151. this.isBlockScope = !!options.block;
  152. this.declarations = Object.create(null);
  153. if (options.params) {
  154. options.params.forEach((param) => {
  155. extractAssignedNames(param).forEach((name) => {
  156. this.declarations[name] = true;
  157. });
  158. });
  159. }
  160. }
  161. addDeclaration(node, isBlockDeclaration, isVar) {
  162. if (!isBlockDeclaration && this.isBlockScope) {
  163. // it's a `var` or function node, and this
  164. // is a block scope, so we need to go up
  165. this.parent.addDeclaration(node, isBlockDeclaration, isVar);
  166. }
  167. else if (node.id) {
  168. extractAssignedNames(node.id).forEach((name) => {
  169. this.declarations[name] = true;
  170. });
  171. }
  172. }
  173. contains(name) {
  174. return this.declarations[name] || (this.parent ? this.parent.contains(name) : false);
  175. }
  176. }
  177. const attachScopes = function attachScopes(ast, propertyName = 'scope') {
  178. let scope = new Scope();
  179. walk(ast, {
  180. enter(n, parent) {
  181. const node = n;
  182. // function foo () {...}
  183. // class Foo {...}
  184. if (/(Function|Class)Declaration/.test(node.type)) {
  185. scope.addDeclaration(node, false, false);
  186. }
  187. // var foo = 1
  188. if (node.type === 'VariableDeclaration') {
  189. const { kind } = node;
  190. const isBlockDeclaration = blockDeclarations[kind];
  191. // don't add const/let declarations in the body of a for loop #113
  192. const parentType = parent ? parent.type : '';
  193. if (!(isBlockDeclaration && /ForOfStatement/.test(parentType))) {
  194. node.declarations.forEach((declaration) => {
  195. scope.addDeclaration(declaration, isBlockDeclaration, true);
  196. });
  197. }
  198. }
  199. let newScope;
  200. // create new function scope
  201. if (/Function/.test(node.type)) {
  202. const func = node;
  203. newScope = new Scope({
  204. parent: scope,
  205. block: false,
  206. params: func.params
  207. });
  208. // named function expressions - the name is considered
  209. // part of the function's scope
  210. if (func.type === 'FunctionExpression' && func.id) {
  211. newScope.addDeclaration(func, false, false);
  212. }
  213. }
  214. // create new block scope
  215. if (node.type === 'BlockStatement' && !/Function/.test(parent.type)) {
  216. newScope = new Scope({
  217. parent: scope,
  218. block: true
  219. });
  220. }
  221. // catch clause has its own block scope
  222. if (node.type === 'CatchClause') {
  223. newScope = new Scope({
  224. parent: scope,
  225. params: node.param ? [node.param] : [],
  226. block: true
  227. });
  228. }
  229. if (newScope) {
  230. Object.defineProperty(node, propertyName, {
  231. value: newScope,
  232. configurable: true
  233. });
  234. scope = newScope;
  235. }
  236. },
  237. leave(n) {
  238. const node = n;
  239. if (node[propertyName])
  240. scope = scope.parent;
  241. }
  242. });
  243. return scope;
  244. };
  245. // Helper since Typescript can't detect readonly arrays with Array.isArray
  246. function isArray(arg) {
  247. return Array.isArray(arg);
  248. }
  249. function ensureArray(thing) {
  250. if (isArray(thing))
  251. return thing;
  252. if (thing == null)
  253. return [];
  254. return [thing];
  255. }
  256. function getMatcherString(id, resolutionBase) {
  257. if (resolutionBase === false) {
  258. return id;
  259. }
  260. // resolve('') is valid and will default to process.cwd()
  261. const basePath = resolve(resolutionBase || '')
  262. .split(sep)
  263. .join('/')
  264. // escape all possible (posix + win) path characters that might interfere with regex
  265. .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
  266. // Note that we use posix.join because:
  267. // 1. the basePath has been normalized to use /
  268. // 2. the incoming glob (id) matcher, also uses /
  269. // otherwise Node will force backslash (\) on windows
  270. return posix.join(basePath, id);
  271. }
  272. const createFilter = function createFilter(include, exclude, options) {
  273. const resolutionBase = options && options.resolve;
  274. const getMatcher = (id) => id instanceof RegExp
  275. ? id
  276. : {
  277. test: (what) => {
  278. // this refactor is a tad overly verbose but makes for easy debugging
  279. const pattern = getMatcherString(id, resolutionBase);
  280. const fn = pm(pattern, { dot: true });
  281. const result = fn(what);
  282. return result;
  283. }
  284. };
  285. const includeMatchers = ensureArray(include).map(getMatcher);
  286. const excludeMatchers = ensureArray(exclude).map(getMatcher);
  287. return function result(id) {
  288. if (typeof id !== 'string')
  289. return false;
  290. if (/\0/.test(id))
  291. return false;
  292. const pathId = id.split(sep).join('/');
  293. for (let i = 0; i < excludeMatchers.length; ++i) {
  294. const matcher = excludeMatchers[i];
  295. if (matcher.test(pathId))
  296. return false;
  297. }
  298. for (let i = 0; i < includeMatchers.length; ++i) {
  299. const matcher = includeMatchers[i];
  300. if (matcher.test(pathId))
  301. return true;
  302. }
  303. return !includeMatchers.length;
  304. };
  305. };
  306. const 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';
  307. const 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';
  308. const forbiddenIdentifiers = new Set(`${reservedWords} ${builtins}`.split(' '));
  309. forbiddenIdentifiers.add('');
  310. const makeLegalIdentifier = function makeLegalIdentifier(str) {
  311. let identifier = str
  312. .replace(/-(\w)/g, (_, letter) => letter.toUpperCase())
  313. .replace(/[^$_a-zA-Z0-9]/g, '_');
  314. if (/\d/.test(identifier[0]) || forbiddenIdentifiers.has(identifier)) {
  315. identifier = `_${identifier}`;
  316. }
  317. return identifier || '_';
  318. };
  319. function stringify(obj) {
  320. return (JSON.stringify(obj) || 'undefined').replace(/[\u2028\u2029]/g, (char) => `\\u${`000${char.charCodeAt(0).toString(16)}`.slice(-4)}`);
  321. }
  322. function serializeArray(arr, indent, baseIndent) {
  323. let output = '[';
  324. const separator = indent ? `\n${baseIndent}${indent}` : '';
  325. for (let i = 0; i < arr.length; i++) {
  326. const key = arr[i];
  327. output += `${i > 0 ? ',' : ''}${separator}${serialize(key, indent, baseIndent + indent)}`;
  328. }
  329. return `${output}${indent ? `\n${baseIndent}` : ''}]`;
  330. }
  331. function serializeObject(obj, indent, baseIndent) {
  332. let output = '{';
  333. const separator = indent ? `\n${baseIndent}${indent}` : '';
  334. const entries = Object.entries(obj);
  335. for (let i = 0; i < entries.length; i++) {
  336. const [key, value] = entries[i];
  337. const stringKey = makeLegalIdentifier(key) === key ? key : stringify(key);
  338. output += `${i > 0 ? ',' : ''}${separator}${stringKey}:${indent ? ' ' : ''}${serialize(value, indent, baseIndent + indent)}`;
  339. }
  340. return `${output}${indent ? `\n${baseIndent}` : ''}}`;
  341. }
  342. function serialize(obj, indent, baseIndent) {
  343. if (obj === Infinity)
  344. return 'Infinity';
  345. if (obj === -Infinity)
  346. return '-Infinity';
  347. if (obj === 0 && 1 / obj === -Infinity)
  348. return '-0';
  349. if (obj instanceof Date)
  350. return `new Date(${obj.getTime()})`;
  351. if (obj instanceof RegExp)
  352. return obj.toString();
  353. if (obj !== obj)
  354. return 'NaN'; // eslint-disable-line no-self-compare
  355. if (Array.isArray(obj))
  356. return serializeArray(obj, indent, baseIndent);
  357. if (obj === null)
  358. return 'null';
  359. if (typeof obj === 'object')
  360. return serializeObject(obj, indent, baseIndent);
  361. return stringify(obj);
  362. }
  363. const dataToEsm = function dataToEsm(data, options = {}) {
  364. const t = options.compact ? '' : 'indent' in options ? options.indent : '\t';
  365. const _ = options.compact ? '' : ' ';
  366. const n = options.compact ? '' : '\n';
  367. const declarationType = options.preferConst ? 'const' : 'var';
  368. if (options.namedExports === false ||
  369. typeof data !== 'object' ||
  370. Array.isArray(data) ||
  371. data instanceof Date ||
  372. data instanceof RegExp ||
  373. data === null) {
  374. const code = serialize(data, options.compact ? null : t, '');
  375. const magic = _ || (/^[{[\-\/]/.test(code) ? '' : ' '); // eslint-disable-line no-useless-escape
  376. return `export default${magic}${code};`;
  377. }
  378. let namedExportCode = '';
  379. const defaultExportRows = [];
  380. for (const [key, value] of Object.entries(data)) {
  381. if (key === makeLegalIdentifier(key)) {
  382. if (options.objectShorthand)
  383. defaultExportRows.push(key);
  384. else
  385. defaultExportRows.push(`${key}:${_}${key}`);
  386. namedExportCode += `export ${declarationType} ${key}${_}=${_}${serialize(value, options.compact ? null : t, '')};${n}`;
  387. }
  388. else {
  389. defaultExportRows.push(`${stringify(key)}:${_}${serialize(value, options.compact ? null : t, '')}`);
  390. }
  391. }
  392. return `${namedExportCode}export default${_}{${n}${t}${defaultExportRows.join(`,${n}${t}`)}${n}};${n}`;
  393. };
  394. // TODO: remove this in next major
  395. var index = {
  396. addExtension,
  397. attachScopes,
  398. createFilter,
  399. dataToEsm,
  400. extractAssignedNames,
  401. makeLegalIdentifier
  402. };
  403. export default index;
  404. export { addExtension, attachScopes, createFilter, dataToEsm, extractAssignedNames, makeLegalIdentifier };