Software zum Installieren eines Smart-Mirror Frameworks , zum Nutzen von hochschulrelevanten Informationen, auf einem Raspberry-Pi.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 58KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880
  1. /*! @author Toru Nagashima <https://github.com/mysticatea> */
  2. 'use strict';
  3. Object.defineProperty(exports, '__esModule', { value: true });
  4. function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
  5. var evk = _interopDefault(require('eslint-visitor-keys'));
  6. /**
  7. * Get the innermost scope which contains a given location.
  8. * @param {Scope} initialScope The initial scope to search.
  9. * @param {Node} node The location to search.
  10. * @returns {Scope} The innermost scope.
  11. */
  12. function getInnermostScope(initialScope, node) {
  13. const location = node.range[0];
  14. let scope = initialScope;
  15. let found = false;
  16. do {
  17. found = false;
  18. for (const childScope of scope.childScopes) {
  19. const range = childScope.block.range;
  20. if (range[0] <= location && location < range[1]) {
  21. scope = childScope;
  22. found = true;
  23. break
  24. }
  25. }
  26. } while (found)
  27. return scope
  28. }
  29. /**
  30. * Find the variable of a given name.
  31. * @param {Scope} initialScope The scope to start finding.
  32. * @param {string|Node} nameOrNode The variable name to find. If this is a Node object then it should be an Identifier node.
  33. * @returns {Variable|null} The found variable or null.
  34. */
  35. function findVariable(initialScope, nameOrNode) {
  36. let name = "";
  37. let scope = initialScope;
  38. if (typeof nameOrNode === "string") {
  39. name = nameOrNode;
  40. } else {
  41. name = nameOrNode.name;
  42. scope = getInnermostScope(scope, nameOrNode);
  43. }
  44. while (scope != null) {
  45. const variable = scope.set.get(name);
  46. if (variable != null) {
  47. return variable
  48. }
  49. scope = scope.upper;
  50. }
  51. return null
  52. }
  53. /**
  54. * Negate the result of `this` calling.
  55. * @param {Token} token The token to check.
  56. * @returns {boolean} `true` if the result of `this(token)` is `false`.
  57. */
  58. function negate0(token) {
  59. return !this(token) //eslint-disable-line no-invalid-this
  60. }
  61. /**
  62. * Creates the negate function of the given function.
  63. * @param {function(Token):boolean} f - The function to negate.
  64. * @returns {function(Token):boolean} Negated function.
  65. */
  66. function negate(f) {
  67. return negate0.bind(f)
  68. }
  69. /**
  70. * Checks if the given token is an arrow token or not.
  71. * @param {Token} token - The token to check.
  72. * @returns {boolean} `true` if the token is an arrow token.
  73. */
  74. function isArrowToken(token) {
  75. return token.value === "=>" && token.type === "Punctuator"
  76. }
  77. /**
  78. * Checks if the given token is a comma token or not.
  79. * @param {Token} token - The token to check.
  80. * @returns {boolean} `true` if the token is a comma token.
  81. */
  82. function isCommaToken(token) {
  83. return token.value === "," && token.type === "Punctuator"
  84. }
  85. /**
  86. * Checks if the given token is a semicolon token or not.
  87. * @param {Token} token - The token to check.
  88. * @returns {boolean} `true` if the token is a semicolon token.
  89. */
  90. function isSemicolonToken(token) {
  91. return token.value === ";" && token.type === "Punctuator"
  92. }
  93. /**
  94. * Checks if the given token is a colon token or not.
  95. * @param {Token} token - The token to check.
  96. * @returns {boolean} `true` if the token is a colon token.
  97. */
  98. function isColonToken(token) {
  99. return token.value === ":" && token.type === "Punctuator"
  100. }
  101. /**
  102. * Checks if the given token is an opening parenthesis token or not.
  103. * @param {Token} token - The token to check.
  104. * @returns {boolean} `true` if the token is an opening parenthesis token.
  105. */
  106. function isOpeningParenToken(token) {
  107. return token.value === "(" && token.type === "Punctuator"
  108. }
  109. /**
  110. * Checks if the given token is a closing parenthesis token or not.
  111. * @param {Token} token - The token to check.
  112. * @returns {boolean} `true` if the token is a closing parenthesis token.
  113. */
  114. function isClosingParenToken(token) {
  115. return token.value === ")" && token.type === "Punctuator"
  116. }
  117. /**
  118. * Checks if the given token is an opening square bracket token or not.
  119. * @param {Token} token - The token to check.
  120. * @returns {boolean} `true` if the token is an opening square bracket token.
  121. */
  122. function isOpeningBracketToken(token) {
  123. return token.value === "[" && token.type === "Punctuator"
  124. }
  125. /**
  126. * Checks if the given token is a closing square bracket token or not.
  127. * @param {Token} token - The token to check.
  128. * @returns {boolean} `true` if the token is a closing square bracket token.
  129. */
  130. function isClosingBracketToken(token) {
  131. return token.value === "]" && token.type === "Punctuator"
  132. }
  133. /**
  134. * Checks if the given token is an opening brace token or not.
  135. * @param {Token} token - The token to check.
  136. * @returns {boolean} `true` if the token is an opening brace token.
  137. */
  138. function isOpeningBraceToken(token) {
  139. return token.value === "{" && token.type === "Punctuator"
  140. }
  141. /**
  142. * Checks if the given token is a closing brace token or not.
  143. * @param {Token} token - The token to check.
  144. * @returns {boolean} `true` if the token is a closing brace token.
  145. */
  146. function isClosingBraceToken(token) {
  147. return token.value === "}" && token.type === "Punctuator"
  148. }
  149. /**
  150. * Checks if the given token is a comment token or not.
  151. * @param {Token} token - The token to check.
  152. * @returns {boolean} `true` if the token is a comment token.
  153. */
  154. function isCommentToken(token) {
  155. return (
  156. token.type === "Line" ||
  157. token.type === "Block" ||
  158. token.type === "Shebang"
  159. )
  160. }
  161. const isNotArrowToken = negate(isArrowToken);
  162. const isNotCommaToken = negate(isCommaToken);
  163. const isNotSemicolonToken = negate(isSemicolonToken);
  164. const isNotColonToken = negate(isColonToken);
  165. const isNotOpeningParenToken = negate(isOpeningParenToken);
  166. const isNotClosingParenToken = negate(isClosingParenToken);
  167. const isNotOpeningBracketToken = negate(isOpeningBracketToken);
  168. const isNotClosingBracketToken = negate(isClosingBracketToken);
  169. const isNotOpeningBraceToken = negate(isOpeningBraceToken);
  170. const isNotClosingBraceToken = negate(isClosingBraceToken);
  171. const isNotCommentToken = negate(isCommentToken);
  172. /**
  173. * Get the `(` token of the given function node.
  174. * @param {Node} node - The function node to get.
  175. * @param {SourceCode} sourceCode - The source code object to get tokens.
  176. * @returns {Token} `(` token.
  177. */
  178. function getOpeningParenOfParams(node, sourceCode) {
  179. return node.id
  180. ? sourceCode.getTokenAfter(node.id, isOpeningParenToken)
  181. : sourceCode.getFirstToken(node, isOpeningParenToken)
  182. }
  183. /**
  184. * Get the location of the given function node for reporting.
  185. * @param {Node} node - The function node to get.
  186. * @param {SourceCode} sourceCode - The source code object to get tokens.
  187. * @returns {string} The location of the function node for reporting.
  188. */
  189. function getFunctionHeadLocation(node, sourceCode) {
  190. const parent = node.parent;
  191. let start = null;
  192. let end = null;
  193. if (node.type === "ArrowFunctionExpression") {
  194. const arrowToken = sourceCode.getTokenBefore(node.body, isArrowToken);
  195. start = arrowToken.loc.start;
  196. end = arrowToken.loc.end;
  197. } else if (
  198. parent.type === "Property" ||
  199. parent.type === "MethodDefinition"
  200. ) {
  201. start = parent.loc.start;
  202. end = getOpeningParenOfParams(node, sourceCode).loc.start;
  203. } else {
  204. start = node.loc.start;
  205. end = getOpeningParenOfParams(node, sourceCode).loc.start;
  206. }
  207. return {
  208. start: Object.assign({}, start),
  209. end: Object.assign({}, end),
  210. }
  211. }
  212. /* globals BigInt, globalThis, global, self, window */
  213. const globalObject =
  214. typeof globalThis !== "undefined"
  215. ? globalThis
  216. : typeof self !== "undefined"
  217. ? self
  218. : typeof window !== "undefined"
  219. ? window
  220. : typeof global !== "undefined"
  221. ? global
  222. : {};
  223. const builtinNames = Object.freeze(
  224. new Set([
  225. "Array",
  226. "ArrayBuffer",
  227. "BigInt",
  228. "BigInt64Array",
  229. "BigUint64Array",
  230. "Boolean",
  231. "DataView",
  232. "Date",
  233. "decodeURI",
  234. "decodeURIComponent",
  235. "encodeURI",
  236. "encodeURIComponent",
  237. "escape",
  238. "Float32Array",
  239. "Float64Array",
  240. "Function",
  241. "Infinity",
  242. "Int16Array",
  243. "Int32Array",
  244. "Int8Array",
  245. "isFinite",
  246. "isNaN",
  247. "isPrototypeOf",
  248. "JSON",
  249. "Map",
  250. "Math",
  251. "NaN",
  252. "Number",
  253. "Object",
  254. "parseFloat",
  255. "parseInt",
  256. "Promise",
  257. "Proxy",
  258. "Reflect",
  259. "RegExp",
  260. "Set",
  261. "String",
  262. "Symbol",
  263. "Uint16Array",
  264. "Uint32Array",
  265. "Uint8Array",
  266. "Uint8ClampedArray",
  267. "undefined",
  268. "unescape",
  269. "WeakMap",
  270. "WeakSet",
  271. ])
  272. );
  273. const callAllowed = new Set(
  274. [
  275. Array.isArray,
  276. typeof BigInt === "function" ? BigInt : undefined,
  277. Boolean,
  278. Date,
  279. Date.parse,
  280. decodeURI,
  281. decodeURIComponent,
  282. encodeURI,
  283. encodeURIComponent,
  284. escape,
  285. isFinite,
  286. isNaN,
  287. isPrototypeOf,
  288. ...Object.getOwnPropertyNames(Math)
  289. .map(k => Math[k])
  290. .filter(f => typeof f === "function"),
  291. Number,
  292. Number.isFinite,
  293. Number.isNaN,
  294. Number.parseFloat,
  295. Number.parseInt,
  296. Object,
  297. Object.entries,
  298. Object.is,
  299. Object.isExtensible,
  300. Object.isFrozen,
  301. Object.isSealed,
  302. Object.keys,
  303. Object.values,
  304. parseFloat,
  305. parseInt,
  306. RegExp,
  307. String,
  308. String.fromCharCode,
  309. String.fromCodePoint,
  310. String.raw,
  311. Symbol,
  312. Symbol.for,
  313. Symbol.keyFor,
  314. unescape,
  315. ].filter(f => typeof f === "function")
  316. );
  317. const callPassThrough = new Set([
  318. Object.freeze,
  319. Object.preventExtensions,
  320. Object.seal,
  321. ]);
  322. /**
  323. * Get the property descriptor.
  324. * @param {object} object The object to get.
  325. * @param {string|number|symbol} name The property name to get.
  326. */
  327. function getPropertyDescriptor(object, name) {
  328. let x = object;
  329. while ((typeof x === "object" || typeof x === "function") && x !== null) {
  330. const d = Object.getOwnPropertyDescriptor(x, name);
  331. if (d) {
  332. return d
  333. }
  334. x = Object.getPrototypeOf(x);
  335. }
  336. return null
  337. }
  338. /**
  339. * Check if a property is getter or not.
  340. * @param {object} object The object to check.
  341. * @param {string|number|symbol} name The property name to check.
  342. */
  343. function isGetter(object, name) {
  344. const d = getPropertyDescriptor(object, name);
  345. return d != null && d.get != null
  346. }
  347. /**
  348. * Get the element values of a given node list.
  349. * @param {Node[]} nodeList The node list to get values.
  350. * @param {Scope|undefined} initialScope The initial scope to find variables.
  351. * @returns {any[]|null} The value list if all nodes are constant. Otherwise, null.
  352. */
  353. function getElementValues(nodeList, initialScope) {
  354. const valueList = [];
  355. for (let i = 0; i < nodeList.length; ++i) {
  356. const elementNode = nodeList[i];
  357. if (elementNode == null) {
  358. valueList.length = i + 1;
  359. } else if (elementNode.type === "SpreadElement") {
  360. const argument = getStaticValueR(elementNode.argument, initialScope);
  361. if (argument == null) {
  362. return null
  363. }
  364. valueList.push(...argument.value);
  365. } else {
  366. const element = getStaticValueR(elementNode, initialScope);
  367. if (element == null) {
  368. return null
  369. }
  370. valueList.push(element.value);
  371. }
  372. }
  373. return valueList
  374. }
  375. const operations = Object.freeze({
  376. ArrayExpression(node, initialScope) {
  377. const elements = getElementValues(node.elements, initialScope);
  378. return elements != null ? { value: elements } : null
  379. },
  380. AssignmentExpression(node, initialScope) {
  381. if (node.operator === "=") {
  382. return getStaticValueR(node.right, initialScope)
  383. }
  384. return null
  385. },
  386. //eslint-disable-next-line complexity
  387. BinaryExpression(node, initialScope) {
  388. if (node.operator === "in" || node.operator === "instanceof") {
  389. // Not supported.
  390. return null
  391. }
  392. const left = getStaticValueR(node.left, initialScope);
  393. const right = getStaticValueR(node.right, initialScope);
  394. if (left != null && right != null) {
  395. switch (node.operator) {
  396. case "==":
  397. return { value: left.value == right.value } //eslint-disable-line eqeqeq
  398. case "!=":
  399. return { value: left.value != right.value } //eslint-disable-line eqeqeq
  400. case "===":
  401. return { value: left.value === right.value }
  402. case "!==":
  403. return { value: left.value !== right.value }
  404. case "<":
  405. return { value: left.value < right.value }
  406. case "<=":
  407. return { value: left.value <= right.value }
  408. case ">":
  409. return { value: left.value > right.value }
  410. case ">=":
  411. return { value: left.value >= right.value }
  412. case "<<":
  413. return { value: left.value << right.value }
  414. case ">>":
  415. return { value: left.value >> right.value }
  416. case ">>>":
  417. return { value: left.value >>> right.value }
  418. case "+":
  419. return { value: left.value + right.value }
  420. case "-":
  421. return { value: left.value - right.value }
  422. case "*":
  423. return { value: left.value * right.value }
  424. case "/":
  425. return { value: left.value / right.value }
  426. case "%":
  427. return { value: left.value % right.value }
  428. case "**":
  429. return { value: Math.pow(left.value, right.value) }
  430. case "|":
  431. return { value: left.value | right.value }
  432. case "^":
  433. return { value: left.value ^ right.value }
  434. case "&":
  435. return { value: left.value & right.value }
  436. // no default
  437. }
  438. }
  439. return null
  440. },
  441. CallExpression(node, initialScope) {
  442. const calleeNode = node.callee;
  443. const args = getElementValues(node.arguments, initialScope);
  444. if (args != null) {
  445. if (calleeNode.type === "MemberExpression") {
  446. const object = getStaticValueR(calleeNode.object, initialScope);
  447. if (object != null) {
  448. if (
  449. object.value == null &&
  450. (object.optional || node.optional)
  451. ) {
  452. return { value: undefined, optional: true }
  453. }
  454. const property = calleeNode.computed
  455. ? getStaticValueR(calleeNode.property, initialScope)
  456. : { value: calleeNode.property.name };
  457. if (property != null) {
  458. const receiver = object.value;
  459. const methodName = property.value;
  460. if (callAllowed.has(receiver[methodName])) {
  461. return { value: receiver[methodName](...args) }
  462. }
  463. if (callPassThrough.has(receiver[methodName])) {
  464. return { value: args[0] }
  465. }
  466. }
  467. }
  468. } else {
  469. const callee = getStaticValueR(calleeNode, initialScope);
  470. if (callee != null) {
  471. if (callee.value == null && node.optional) {
  472. return { value: undefined, optional: true }
  473. }
  474. const func = callee.value;
  475. if (callAllowed.has(func)) {
  476. return { value: func(...args) }
  477. }
  478. if (callPassThrough.has(func)) {
  479. return { value: args[0] }
  480. }
  481. }
  482. }
  483. }
  484. return null
  485. },
  486. ConditionalExpression(node, initialScope) {
  487. const test = getStaticValueR(node.test, initialScope);
  488. if (test != null) {
  489. return test.value
  490. ? getStaticValueR(node.consequent, initialScope)
  491. : getStaticValueR(node.alternate, initialScope)
  492. }
  493. return null
  494. },
  495. ExpressionStatement(node, initialScope) {
  496. return getStaticValueR(node.expression, initialScope)
  497. },
  498. Identifier(node, initialScope) {
  499. if (initialScope != null) {
  500. const variable = findVariable(initialScope, node);
  501. // Built-in globals.
  502. if (
  503. variable != null &&
  504. variable.defs.length === 0 &&
  505. builtinNames.has(variable.name) &&
  506. variable.name in globalObject
  507. ) {
  508. return { value: globalObject[variable.name] }
  509. }
  510. // Constants.
  511. if (variable != null && variable.defs.length === 1) {
  512. const def = variable.defs[0];
  513. if (
  514. def.parent &&
  515. def.parent.kind === "const" &&
  516. // TODO(mysticatea): don't support destructuring here.
  517. def.node.id.type === "Identifier"
  518. ) {
  519. return getStaticValueR(def.node.init, initialScope)
  520. }
  521. }
  522. }
  523. return null
  524. },
  525. Literal(node) {
  526. //istanbul ignore if : this is implementation-specific behavior.
  527. if ((node.regex != null || node.bigint != null) && node.value == null) {
  528. // It was a RegExp/BigInt literal, but Node.js didn't support it.
  529. return null
  530. }
  531. return { value: node.value }
  532. },
  533. LogicalExpression(node, initialScope) {
  534. const left = getStaticValueR(node.left, initialScope);
  535. if (left != null) {
  536. if (
  537. (node.operator === "||" && Boolean(left.value) === true) ||
  538. (node.operator === "&&" && Boolean(left.value) === false) ||
  539. (node.operator === "??" && left.value != null)
  540. ) {
  541. return left
  542. }
  543. const right = getStaticValueR(node.right, initialScope);
  544. if (right != null) {
  545. return right
  546. }
  547. }
  548. return null
  549. },
  550. MemberExpression(node, initialScope) {
  551. const object = getStaticValueR(node.object, initialScope);
  552. if (object != null) {
  553. if (object.value == null && (object.optional || node.optional)) {
  554. return { value: undefined, optional: true }
  555. }
  556. const property = node.computed
  557. ? getStaticValueR(node.property, initialScope)
  558. : { value: node.property.name };
  559. if (property != null && !isGetter(object.value, property.value)) {
  560. return { value: object.value[property.value] }
  561. }
  562. }
  563. return null
  564. },
  565. ChainExpression(node, initialScope) {
  566. const expression = getStaticValueR(node.expression, initialScope);
  567. if (expression != null) {
  568. return { value: expression.value }
  569. }
  570. return null
  571. },
  572. NewExpression(node, initialScope) {
  573. const callee = getStaticValueR(node.callee, initialScope);
  574. const args = getElementValues(node.arguments, initialScope);
  575. if (callee != null && args != null) {
  576. const Func = callee.value;
  577. if (callAllowed.has(Func)) {
  578. return { value: new Func(...args) }
  579. }
  580. }
  581. return null
  582. },
  583. ObjectExpression(node, initialScope) {
  584. const object = {};
  585. for (const propertyNode of node.properties) {
  586. if (propertyNode.type === "Property") {
  587. if (propertyNode.kind !== "init") {
  588. return null
  589. }
  590. const key = propertyNode.computed
  591. ? getStaticValueR(propertyNode.key, initialScope)
  592. : { value: propertyNode.key.name };
  593. const value = getStaticValueR(propertyNode.value, initialScope);
  594. if (key == null || value == null) {
  595. return null
  596. }
  597. object[key.value] = value.value;
  598. } else if (
  599. propertyNode.type === "SpreadElement" ||
  600. propertyNode.type === "ExperimentalSpreadProperty"
  601. ) {
  602. const argument = getStaticValueR(
  603. propertyNode.argument,
  604. initialScope
  605. );
  606. if (argument == null) {
  607. return null
  608. }
  609. Object.assign(object, argument.value);
  610. } else {
  611. return null
  612. }
  613. }
  614. return { value: object }
  615. },
  616. SequenceExpression(node, initialScope) {
  617. const last = node.expressions[node.expressions.length - 1];
  618. return getStaticValueR(last, initialScope)
  619. },
  620. TaggedTemplateExpression(node, initialScope) {
  621. const tag = getStaticValueR(node.tag, initialScope);
  622. const expressions = getElementValues(
  623. node.quasi.expressions,
  624. initialScope
  625. );
  626. if (tag != null && expressions != null) {
  627. const func = tag.value;
  628. const strings = node.quasi.quasis.map(q => q.value.cooked);
  629. strings.raw = node.quasi.quasis.map(q => q.value.raw);
  630. if (func === String.raw) {
  631. return { value: func(strings, ...expressions) }
  632. }
  633. }
  634. return null
  635. },
  636. TemplateLiteral(node, initialScope) {
  637. const expressions = getElementValues(node.expressions, initialScope);
  638. if (expressions != null) {
  639. let value = node.quasis[0].value.cooked;
  640. for (let i = 0; i < expressions.length; ++i) {
  641. value += expressions[i];
  642. value += node.quasis[i + 1].value.cooked;
  643. }
  644. return { value }
  645. }
  646. return null
  647. },
  648. UnaryExpression(node, initialScope) {
  649. if (node.operator === "delete") {
  650. // Not supported.
  651. return null
  652. }
  653. if (node.operator === "void") {
  654. return { value: undefined }
  655. }
  656. const arg = getStaticValueR(node.argument, initialScope);
  657. if (arg != null) {
  658. switch (node.operator) {
  659. case "-":
  660. return { value: -arg.value }
  661. case "+":
  662. return { value: +arg.value } //eslint-disable-line no-implicit-coercion
  663. case "!":
  664. return { value: !arg.value }
  665. case "~":
  666. return { value: ~arg.value }
  667. case "typeof":
  668. return { value: typeof arg.value }
  669. // no default
  670. }
  671. }
  672. return null
  673. },
  674. });
  675. /**
  676. * Get the value of a given node if it's a static value.
  677. * @param {Node} node The node to get.
  678. * @param {Scope|undefined} initialScope The scope to start finding variable.
  679. * @returns {{value:any}|{value:undefined,optional?:true}|null} The static value of the node, or `null`.
  680. */
  681. function getStaticValueR(node, initialScope) {
  682. if (node != null && Object.hasOwnProperty.call(operations, node.type)) {
  683. return operations[node.type](node, initialScope)
  684. }
  685. return null
  686. }
  687. /**
  688. * Get the value of a given node if it's a static value.
  689. * @param {Node} node The node to get.
  690. * @param {Scope} [initialScope] The scope to start finding variable. Optional. If this scope was given, this tries to resolve identifier references which are in the given node as much as possible.
  691. * @returns {{value:any}|{value:undefined,optional?:true}|null} The static value of the node, or `null`.
  692. */
  693. function getStaticValue(node, initialScope = null) {
  694. try {
  695. return getStaticValueR(node, initialScope)
  696. } catch (_error) {
  697. return null
  698. }
  699. }
  700. /**
  701. * Get the value of a given node if it's a literal or a template literal.
  702. * @param {Node} node The node to get.
  703. * @param {Scope} [initialScope] The scope to start finding variable. Optional. If the node is an Identifier node and this scope was given, this checks the variable of the identifier, and returns the value of it if the variable is a constant.
  704. * @returns {string|null} The value of the node, or `null`.
  705. */
  706. function getStringIfConstant(node, initialScope = null) {
  707. // Handle the literals that the platform doesn't support natively.
  708. if (node && node.type === "Literal" && node.value === null) {
  709. if (node.regex) {
  710. return `/${node.regex.pattern}/${node.regex.flags}`
  711. }
  712. if (node.bigint) {
  713. return node.bigint
  714. }
  715. }
  716. const evaluated = getStaticValue(node, initialScope);
  717. return evaluated && String(evaluated.value)
  718. }
  719. /**
  720. * Get the property name from a MemberExpression node or a Property node.
  721. * @param {Node} node The node to get.
  722. * @param {Scope} [initialScope] The scope to start finding variable. Optional. If the node is a computed property node and this scope was given, this checks the computed property name by the `getStringIfConstant` function with the scope, and returns the value of it.
  723. * @returns {string|null} The property name of the node.
  724. */
  725. function getPropertyName(node, initialScope) {
  726. switch (node.type) {
  727. case "MemberExpression":
  728. if (node.computed) {
  729. return getStringIfConstant(node.property, initialScope)
  730. }
  731. return node.property.name
  732. case "Property":
  733. case "MethodDefinition":
  734. if (node.computed) {
  735. return getStringIfConstant(node.key, initialScope)
  736. }
  737. if (node.key.type === "Literal") {
  738. return String(node.key.value)
  739. }
  740. return node.key.name
  741. // no default
  742. }
  743. return null
  744. }
  745. /**
  746. * Get the name and kind of the given function node.
  747. * @param {ASTNode} node - The function node to get.
  748. * @returns {string} The name and kind of the function node.
  749. */
  750. function getFunctionNameWithKind(node) {
  751. const parent = node.parent;
  752. const tokens = [];
  753. if (parent.type === "MethodDefinition" && parent.static) {
  754. tokens.push("static");
  755. }
  756. if (node.async) {
  757. tokens.push("async");
  758. }
  759. if (node.generator) {
  760. tokens.push("generator");
  761. }
  762. if (node.type === "ArrowFunctionExpression") {
  763. tokens.push("arrow", "function");
  764. } else if (
  765. parent.type === "Property" ||
  766. parent.type === "MethodDefinition"
  767. ) {
  768. if (parent.kind === "constructor") {
  769. return "constructor"
  770. }
  771. if (parent.kind === "get") {
  772. tokens.push("getter");
  773. } else if (parent.kind === "set") {
  774. tokens.push("setter");
  775. } else {
  776. tokens.push("method");
  777. }
  778. } else {
  779. tokens.push("function");
  780. }
  781. if (node.id) {
  782. tokens.push(`'${node.id.name}'`);
  783. } else {
  784. const name = getPropertyName(parent);
  785. if (name) {
  786. tokens.push(`'${name}'`);
  787. }
  788. }
  789. if (node.type === "ArrowFunctionExpression") {
  790. if (
  791. parent.type === "VariableDeclarator" &&
  792. parent.id &&
  793. parent.id.type === "Identifier"
  794. ) {
  795. tokens.push(`'${parent.id.name}'`);
  796. }
  797. if (
  798. parent.type === "AssignmentExpression" &&
  799. parent.left &&
  800. parent.left.type === "Identifier"
  801. ) {
  802. tokens.push(`'${parent.left.name}'`);
  803. }
  804. }
  805. return tokens.join(" ")
  806. }
  807. const typeConversionBinaryOps = Object.freeze(
  808. new Set([
  809. "==",
  810. "!=",
  811. "<",
  812. "<=",
  813. ">",
  814. ">=",
  815. "<<",
  816. ">>",
  817. ">>>",
  818. "+",
  819. "-",
  820. "*",
  821. "/",
  822. "%",
  823. "|",
  824. "^",
  825. "&",
  826. "in",
  827. ])
  828. );
  829. const typeConversionUnaryOps = Object.freeze(new Set(["-", "+", "!", "~"]));
  830. /**
  831. * Check whether the given value is an ASTNode or not.
  832. * @param {any} x The value to check.
  833. * @returns {boolean} `true` if the value is an ASTNode.
  834. */
  835. function isNode(x) {
  836. return x !== null && typeof x === "object" && typeof x.type === "string"
  837. }
  838. const visitor = Object.freeze(
  839. Object.assign(Object.create(null), {
  840. $visit(node, options, visitorKeys) {
  841. const { type } = node;
  842. if (typeof this[type] === "function") {
  843. return this[type](node, options, visitorKeys)
  844. }
  845. return this.$visitChildren(node, options, visitorKeys)
  846. },
  847. $visitChildren(node, options, visitorKeys) {
  848. const { type } = node;
  849. for (const key of visitorKeys[type] || evk.getKeys(node)) {
  850. const value = node[key];
  851. if (Array.isArray(value)) {
  852. for (const element of value) {
  853. if (
  854. isNode(element) &&
  855. this.$visit(element, options, visitorKeys)
  856. ) {
  857. return true
  858. }
  859. }
  860. } else if (
  861. isNode(value) &&
  862. this.$visit(value, options, visitorKeys)
  863. ) {
  864. return true
  865. }
  866. }
  867. return false
  868. },
  869. ArrowFunctionExpression() {
  870. return false
  871. },
  872. AssignmentExpression() {
  873. return true
  874. },
  875. AwaitExpression() {
  876. return true
  877. },
  878. BinaryExpression(node, options, visitorKeys) {
  879. if (
  880. options.considerImplicitTypeConversion &&
  881. typeConversionBinaryOps.has(node.operator) &&
  882. (node.left.type !== "Literal" || node.right.type !== "Literal")
  883. ) {
  884. return true
  885. }
  886. return this.$visitChildren(node, options, visitorKeys)
  887. },
  888. CallExpression() {
  889. return true
  890. },
  891. FunctionExpression() {
  892. return false
  893. },
  894. ImportExpression() {
  895. return true
  896. },
  897. MemberExpression(node, options, visitorKeys) {
  898. if (options.considerGetters) {
  899. return true
  900. }
  901. if (
  902. options.considerImplicitTypeConversion &&
  903. node.computed &&
  904. node.property.type !== "Literal"
  905. ) {
  906. return true
  907. }
  908. return this.$visitChildren(node, options, visitorKeys)
  909. },
  910. MethodDefinition(node, options, visitorKeys) {
  911. if (
  912. options.considerImplicitTypeConversion &&
  913. node.computed &&
  914. node.key.type !== "Literal"
  915. ) {
  916. return true
  917. }
  918. return this.$visitChildren(node, options, visitorKeys)
  919. },
  920. NewExpression() {
  921. return true
  922. },
  923. Property(node, options, visitorKeys) {
  924. if (
  925. options.considerImplicitTypeConversion &&
  926. node.computed &&
  927. node.key.type !== "Literal"
  928. ) {
  929. return true
  930. }
  931. return this.$visitChildren(node, options, visitorKeys)
  932. },
  933. UnaryExpression(node, options, visitorKeys) {
  934. if (node.operator === "delete") {
  935. return true
  936. }
  937. if (
  938. options.considerImplicitTypeConversion &&
  939. typeConversionUnaryOps.has(node.operator) &&
  940. node.argument.type !== "Literal"
  941. ) {
  942. return true
  943. }
  944. return this.$visitChildren(node, options, visitorKeys)
  945. },
  946. UpdateExpression() {
  947. return true
  948. },
  949. YieldExpression() {
  950. return true
  951. },
  952. })
  953. );
  954. /**
  955. * Check whether a given node has any side effect or not.
  956. * @param {Node} node The node to get.
  957. * @param {SourceCode} sourceCode The source code object.
  958. * @param {object} [options] The option object.
  959. * @param {boolean} [options.considerGetters=false] If `true` then it considers member accesses as the node which has side effects.
  960. * @param {boolean} [options.considerImplicitTypeConversion=false] If `true` then it considers implicit type conversion as the node which has side effects.
  961. * @param {object} [options.visitorKeys=evk.KEYS] The keys to traverse nodes. Use `context.getSourceCode().visitorKeys`.
  962. * @returns {boolean} `true` if the node has a certain side effect.
  963. */
  964. function hasSideEffect(
  965. node,
  966. sourceCode,
  967. { considerGetters = false, considerImplicitTypeConversion = false } = {}
  968. ) {
  969. return visitor.$visit(
  970. node,
  971. { considerGetters, considerImplicitTypeConversion },
  972. sourceCode.visitorKeys || evk.KEYS
  973. )
  974. }
  975. /**
  976. * Get the left parenthesis of the parent node syntax if it exists.
  977. * E.g., `if (a) {}` then the `(`.
  978. * @param {Node} node The AST node to check.
  979. * @param {SourceCode} sourceCode The source code object to get tokens.
  980. * @returns {Token|null} The left parenthesis of the parent node syntax
  981. */
  982. function getParentSyntaxParen(node, sourceCode) {
  983. const parent = node.parent;
  984. switch (parent.type) {
  985. case "CallExpression":
  986. case "NewExpression":
  987. if (parent.arguments.length === 1 && parent.arguments[0] === node) {
  988. return sourceCode.getTokenAfter(
  989. parent.callee,
  990. isOpeningParenToken
  991. )
  992. }
  993. return null
  994. case "DoWhileStatement":
  995. if (parent.test === node) {
  996. return sourceCode.getTokenAfter(
  997. parent.body,
  998. isOpeningParenToken
  999. )
  1000. }
  1001. return null
  1002. case "IfStatement":
  1003. case "WhileStatement":
  1004. if (parent.test === node) {
  1005. return sourceCode.getFirstToken(parent, 1)
  1006. }
  1007. return null
  1008. case "ImportExpression":
  1009. if (parent.source === node) {
  1010. return sourceCode.getFirstToken(parent, 1)
  1011. }
  1012. return null
  1013. case "SwitchStatement":
  1014. if (parent.discriminant === node) {
  1015. return sourceCode.getFirstToken(parent, 1)
  1016. }
  1017. return null
  1018. case "WithStatement":
  1019. if (parent.object === node) {
  1020. return sourceCode.getFirstToken(parent, 1)
  1021. }
  1022. return null
  1023. default:
  1024. return null
  1025. }
  1026. }
  1027. /**
  1028. * Check whether a given node is parenthesized or not.
  1029. * @param {number} times The number of parantheses.
  1030. * @param {Node} node The AST node to check.
  1031. * @param {SourceCode} sourceCode The source code object to get tokens.
  1032. * @returns {boolean} `true` if the node is parenthesized the given times.
  1033. */
  1034. /**
  1035. * Check whether a given node is parenthesized or not.
  1036. * @param {Node} node The AST node to check.
  1037. * @param {SourceCode} sourceCode The source code object to get tokens.
  1038. * @returns {boolean} `true` if the node is parenthesized.
  1039. */
  1040. function isParenthesized(
  1041. timesOrNode,
  1042. nodeOrSourceCode,
  1043. optionalSourceCode
  1044. ) {
  1045. let times, node, sourceCode, maybeLeftParen, maybeRightParen;
  1046. if (typeof timesOrNode === "number") {
  1047. times = timesOrNode | 0;
  1048. node = nodeOrSourceCode;
  1049. sourceCode = optionalSourceCode;
  1050. if (!(times >= 1)) {
  1051. throw new TypeError("'times' should be a positive integer.")
  1052. }
  1053. } else {
  1054. times = 1;
  1055. node = timesOrNode;
  1056. sourceCode = nodeOrSourceCode;
  1057. }
  1058. if (node == null) {
  1059. return false
  1060. }
  1061. maybeLeftParen = maybeRightParen = node;
  1062. do {
  1063. maybeLeftParen = sourceCode.getTokenBefore(maybeLeftParen);
  1064. maybeRightParen = sourceCode.getTokenAfter(maybeRightParen);
  1065. } while (
  1066. maybeLeftParen != null &&
  1067. maybeRightParen != null &&
  1068. isOpeningParenToken(maybeLeftParen) &&
  1069. isClosingParenToken(maybeRightParen) &&
  1070. // Avoid false positive such as `if (a) {}`
  1071. maybeLeftParen !== getParentSyntaxParen(node, sourceCode) &&
  1072. --times > 0
  1073. )
  1074. return times === 0
  1075. }
  1076. /**
  1077. * @author Toru Nagashima <https://github.com/mysticatea>
  1078. * See LICENSE file in root directory for full license.
  1079. */
  1080. const placeholder = /\$(?:[$&`']|[1-9][0-9]?)/gu;
  1081. /** @type {WeakMap<PatternMatcher, {pattern:RegExp,escaped:boolean}>} */
  1082. const internal = new WeakMap();
  1083. /**
  1084. * Check whether a given character is escaped or not.
  1085. * @param {string} str The string to check.
  1086. * @param {number} index The location of the character to check.
  1087. * @returns {boolean} `true` if the character is escaped.
  1088. */
  1089. function isEscaped(str, index) {
  1090. let escaped = false;
  1091. for (let i = index - 1; i >= 0 && str.charCodeAt(i) === 0x5c; --i) {
  1092. escaped = !escaped;
  1093. }
  1094. return escaped
  1095. }
  1096. /**
  1097. * Replace a given string by a given matcher.
  1098. * @param {PatternMatcher} matcher The pattern matcher.
  1099. * @param {string} str The string to be replaced.
  1100. * @param {string} replacement The new substring to replace each matched part.
  1101. * @returns {string} The replaced string.
  1102. */
  1103. function replaceS(matcher, str, replacement) {
  1104. const chunks = [];
  1105. let index = 0;
  1106. /** @type {RegExpExecArray} */
  1107. let match = null;
  1108. /**
  1109. * @param {string} key The placeholder.
  1110. * @returns {string} The replaced string.
  1111. */
  1112. function replacer(key) {
  1113. switch (key) {
  1114. case "$$":
  1115. return "$"
  1116. case "$&":
  1117. return match[0]
  1118. case "$`":
  1119. return str.slice(0, match.index)
  1120. case "$'":
  1121. return str.slice(match.index + match[0].length)
  1122. default: {
  1123. const i = key.slice(1);
  1124. if (i in match) {
  1125. return match[i]
  1126. }
  1127. return key
  1128. }
  1129. }
  1130. }
  1131. for (match of matcher.execAll(str)) {
  1132. chunks.push(str.slice(index, match.index));
  1133. chunks.push(replacement.replace(placeholder, replacer));
  1134. index = match.index + match[0].length;
  1135. }
  1136. chunks.push(str.slice(index));
  1137. return chunks.join("")
  1138. }
  1139. /**
  1140. * Replace a given string by a given matcher.
  1141. * @param {PatternMatcher} matcher The pattern matcher.
  1142. * @param {string} str The string to be replaced.
  1143. * @param {(...strs[])=>string} replace The function to replace each matched part.
  1144. * @returns {string} The replaced string.
  1145. */
  1146. function replaceF(matcher, str, replace) {
  1147. const chunks = [];
  1148. let index = 0;
  1149. for (const match of matcher.execAll(str)) {
  1150. chunks.push(str.slice(index, match.index));
  1151. chunks.push(String(replace(...match, match.index, match.input)));
  1152. index = match.index + match[0].length;
  1153. }
  1154. chunks.push(str.slice(index));
  1155. return chunks.join("")
  1156. }
  1157. /**
  1158. * The class to find patterns as considering escape sequences.
  1159. */
  1160. class PatternMatcher {
  1161. /**
  1162. * Initialize this matcher.
  1163. * @param {RegExp} pattern The pattern to match.
  1164. * @param {{escaped:boolean}} options The options.
  1165. */
  1166. constructor(pattern, { escaped = false } = {}) {
  1167. if (!(pattern instanceof RegExp)) {
  1168. throw new TypeError("'pattern' should be a RegExp instance.")
  1169. }
  1170. if (!pattern.flags.includes("g")) {
  1171. throw new Error("'pattern' should contains 'g' flag.")
  1172. }
  1173. internal.set(this, {
  1174. pattern: new RegExp(pattern.source, pattern.flags),
  1175. escaped: Boolean(escaped),
  1176. });
  1177. }
  1178. /**
  1179. * Find the pattern in a given string.
  1180. * @param {string} str The string to find.
  1181. * @returns {IterableIterator<RegExpExecArray>} The iterator which iterate the matched information.
  1182. */
  1183. *execAll(str) {
  1184. const { pattern, escaped } = internal.get(this);
  1185. let match = null;
  1186. let lastIndex = 0;
  1187. pattern.lastIndex = 0;
  1188. while ((match = pattern.exec(str)) != null) {
  1189. if (escaped || !isEscaped(str, match.index)) {
  1190. lastIndex = pattern.lastIndex;
  1191. yield match;
  1192. pattern.lastIndex = lastIndex;
  1193. }
  1194. }
  1195. }
  1196. /**
  1197. * Check whether the pattern is found in a given string.
  1198. * @param {string} str The string to check.
  1199. * @returns {boolean} `true` if the pattern was found in the string.
  1200. */
  1201. test(str) {
  1202. const it = this.execAll(str);
  1203. const ret = it.next();
  1204. return !ret.done
  1205. }
  1206. /**
  1207. * Replace a given string.
  1208. * @param {string} str The string to be replaced.
  1209. * @param {(string|((...strs:string[])=>string))} replacer The string or function to replace. This is the same as the 2nd argument of `String.prototype.replace`.
  1210. * @returns {string} The replaced string.
  1211. */
  1212. [Symbol.replace](str, replacer) {
  1213. return typeof replacer === "function"
  1214. ? replaceF(this, String(str), replacer)
  1215. : replaceS(this, String(str), String(replacer))
  1216. }
  1217. }
  1218. const IMPORT_TYPE = /^(?:Import|Export(?:All|Default|Named))Declaration$/u;
  1219. const has = Function.call.bind(Object.hasOwnProperty);
  1220. const READ = Symbol("read");
  1221. const CALL = Symbol("call");
  1222. const CONSTRUCT = Symbol("construct");
  1223. const ESM = Symbol("esm");
  1224. const requireCall = { require: { [CALL]: true } };
  1225. /**
  1226. * Check whether a given variable is modified or not.
  1227. * @param {Variable} variable The variable to check.
  1228. * @returns {boolean} `true` if the variable is modified.
  1229. */
  1230. function isModifiedGlobal(variable) {
  1231. return (
  1232. variable == null ||
  1233. variable.defs.length !== 0 ||
  1234. variable.references.some(r => r.isWrite())
  1235. )
  1236. }
  1237. /**
  1238. * Check if the value of a given node is passed through to the parent syntax as-is.
  1239. * For example, `a` and `b` in (`a || b` and `c ? a : b`) are passed through.
  1240. * @param {Node} node A node to check.
  1241. * @returns {boolean} `true` if the node is passed through.
  1242. */
  1243. function isPassThrough(node) {
  1244. const parent = node.parent;
  1245. switch (parent && parent.type) {
  1246. case "ConditionalExpression":
  1247. return parent.consequent === node || parent.alternate === node
  1248. case "LogicalExpression":
  1249. return true
  1250. case "SequenceExpression":
  1251. return parent.expressions[parent.expressions.length - 1] === node
  1252. case "ChainExpression":
  1253. return true
  1254. default:
  1255. return false
  1256. }
  1257. }
  1258. /**
  1259. * The reference tracker.
  1260. */
  1261. class ReferenceTracker {
  1262. /**
  1263. * Initialize this tracker.
  1264. * @param {Scope} globalScope The global scope.
  1265. * @param {object} [options] The options.
  1266. * @param {"legacy"|"strict"} [options.mode="strict"] The mode to determine the ImportDeclaration's behavior for CJS modules.
  1267. * @param {string[]} [options.globalObjectNames=["global","globalThis","self","window"]] The variable names for Global Object.
  1268. */
  1269. constructor(
  1270. globalScope,
  1271. {
  1272. mode = "strict",
  1273. globalObjectNames = ["global", "globalThis", "self", "window"],
  1274. } = {}
  1275. ) {
  1276. this.variableStack = [];
  1277. this.globalScope = globalScope;
  1278. this.mode = mode;
  1279. this.globalObjectNames = globalObjectNames.slice(0);
  1280. }
  1281. /**
  1282. * Iterate the references of global variables.
  1283. * @param {object} traceMap The trace map.
  1284. * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
  1285. */
  1286. *iterateGlobalReferences(traceMap) {
  1287. for (const key of Object.keys(traceMap)) {
  1288. const nextTraceMap = traceMap[key];
  1289. const path = [key];
  1290. const variable = this.globalScope.set.get(key);
  1291. if (isModifiedGlobal(variable)) {
  1292. continue
  1293. }
  1294. yield* this._iterateVariableReferences(
  1295. variable,
  1296. path,
  1297. nextTraceMap,
  1298. true
  1299. );
  1300. }
  1301. for (const key of this.globalObjectNames) {
  1302. const path = [];
  1303. const variable = this.globalScope.set.get(key);
  1304. if (isModifiedGlobal(variable)) {
  1305. continue
  1306. }
  1307. yield* this._iterateVariableReferences(
  1308. variable,
  1309. path,
  1310. traceMap,
  1311. false
  1312. );
  1313. }
  1314. }
  1315. /**
  1316. * Iterate the references of CommonJS modules.
  1317. * @param {object} traceMap The trace map.
  1318. * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
  1319. */
  1320. *iterateCjsReferences(traceMap) {
  1321. for (const { node } of this.iterateGlobalReferences(requireCall)) {
  1322. const key = getStringIfConstant(node.arguments[0]);
  1323. if (key == null || !has(traceMap, key)) {
  1324. continue
  1325. }
  1326. const nextTraceMap = traceMap[key];
  1327. const path = [key];
  1328. if (nextTraceMap[READ]) {
  1329. yield {
  1330. node,
  1331. path,
  1332. type: READ,
  1333. info: nextTraceMap[READ],
  1334. };
  1335. }
  1336. yield* this._iteratePropertyReferences(node, path, nextTraceMap);
  1337. }
  1338. }
  1339. /**
  1340. * Iterate the references of ES modules.
  1341. * @param {object} traceMap The trace map.
  1342. * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
  1343. */
  1344. *iterateEsmReferences(traceMap) {
  1345. const programNode = this.globalScope.block;
  1346. for (const node of programNode.body) {
  1347. if (!IMPORT_TYPE.test(node.type) || node.source == null) {
  1348. continue
  1349. }
  1350. const moduleId = node.source.value;
  1351. if (!has(traceMap, moduleId)) {
  1352. continue
  1353. }
  1354. const nextTraceMap = traceMap[moduleId];
  1355. const path = [moduleId];
  1356. if (nextTraceMap[READ]) {
  1357. yield { node, path, type: READ, info: nextTraceMap[READ] };
  1358. }
  1359. if (node.type === "ExportAllDeclaration") {
  1360. for (const key of Object.keys(nextTraceMap)) {
  1361. const exportTraceMap = nextTraceMap[key];
  1362. if (exportTraceMap[READ]) {
  1363. yield {
  1364. node,
  1365. path: path.concat(key),
  1366. type: READ,
  1367. info: exportTraceMap[READ],
  1368. };
  1369. }
  1370. }
  1371. } else {
  1372. for (const specifier of node.specifiers) {
  1373. const esm = has(nextTraceMap, ESM);
  1374. const it = this._iterateImportReferences(
  1375. specifier,
  1376. path,
  1377. esm
  1378. ? nextTraceMap
  1379. : this.mode === "legacy"
  1380. ? Object.assign(
  1381. { default: nextTraceMap },
  1382. nextTraceMap
  1383. )
  1384. : { default: nextTraceMap }
  1385. );
  1386. if (esm) {
  1387. yield* it;
  1388. } else {
  1389. for (const report of it) {
  1390. report.path = report.path.filter(exceptDefault);
  1391. if (
  1392. report.path.length >= 2 ||
  1393. report.type !== READ
  1394. ) {
  1395. yield report;
  1396. }
  1397. }
  1398. }
  1399. }
  1400. }
  1401. }
  1402. }
  1403. /**
  1404. * Iterate the references for a given variable.
  1405. * @param {Variable} variable The variable to iterate that references.
  1406. * @param {string[]} path The current path.
  1407. * @param {object} traceMap The trace map.
  1408. * @param {boolean} shouldReport = The flag to report those references.
  1409. * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
  1410. */
  1411. *_iterateVariableReferences(variable, path, traceMap, shouldReport) {
  1412. if (this.variableStack.includes(variable)) {
  1413. return
  1414. }
  1415. this.variableStack.push(variable);
  1416. try {
  1417. for (const reference of variable.references) {
  1418. if (!reference.isRead()) {
  1419. continue
  1420. }
  1421. const node = reference.identifier;
  1422. if (shouldReport && traceMap[READ]) {
  1423. yield { node, path, type: READ, info: traceMap[READ] };
  1424. }
  1425. yield* this._iteratePropertyReferences(node, path, traceMap);
  1426. }
  1427. } finally {
  1428. this.variableStack.pop();
  1429. }
  1430. }
  1431. /**
  1432. * Iterate the references for a given AST node.
  1433. * @param rootNode The AST node to iterate references.
  1434. * @param {string[]} path The current path.
  1435. * @param {object} traceMap The trace map.
  1436. * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
  1437. */
  1438. //eslint-disable-next-line complexity
  1439. *_iteratePropertyReferences(rootNode, path, traceMap) {
  1440. let node = rootNode;
  1441. while (isPassThrough(node)) {
  1442. node = node.parent;
  1443. }
  1444. const parent = node.parent;
  1445. if (parent.type === "MemberExpression") {
  1446. if (parent.object === node) {
  1447. const key = getPropertyName(parent);
  1448. if (key == null || !has(traceMap, key)) {
  1449. return
  1450. }
  1451. path = path.concat(key); //eslint-disable-line no-param-reassign
  1452. const nextTraceMap = traceMap[key];
  1453. if (nextTraceMap[READ]) {
  1454. yield {
  1455. node: parent,
  1456. path,
  1457. type: READ,
  1458. info: nextTraceMap[READ],
  1459. };
  1460. }
  1461. yield* this._iteratePropertyReferences(
  1462. parent,
  1463. path,
  1464. nextTraceMap
  1465. );
  1466. }
  1467. return
  1468. }
  1469. if (parent.type === "CallExpression") {
  1470. if (parent.callee === node && traceMap[CALL]) {
  1471. yield { node: parent, path, type: CALL, info: traceMap[CALL] };
  1472. }
  1473. return
  1474. }
  1475. if (parent.type === "NewExpression") {
  1476. if (parent.callee === node && traceMap[CONSTRUCT]) {
  1477. yield {
  1478. node: parent,
  1479. path,
  1480. type: CONSTRUCT,
  1481. info: traceMap[CONSTRUCT],
  1482. };
  1483. }
  1484. return
  1485. }
  1486. if (parent.type === "AssignmentExpression") {
  1487. if (parent.right === node) {
  1488. yield* this._iterateLhsReferences(parent.left, path, traceMap);
  1489. yield* this._iteratePropertyReferences(parent, path, traceMap);
  1490. }
  1491. return
  1492. }
  1493. if (parent.type === "AssignmentPattern") {
  1494. if (parent.right === node) {
  1495. yield* this._iterateLhsReferences(parent.left, path, traceMap);
  1496. }
  1497. return
  1498. }
  1499. if (parent.type === "VariableDeclarator") {
  1500. if (parent.init === node) {
  1501. yield* this._iterateLhsReferences(parent.id, path, traceMap);
  1502. }
  1503. }
  1504. }
  1505. /**
  1506. * Iterate the references for a given Pattern node.
  1507. * @param {Node} patternNode The Pattern node to iterate references.
  1508. * @param {string[]} path The current path.
  1509. * @param {object} traceMap The trace map.
  1510. * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
  1511. */
  1512. *_iterateLhsReferences(patternNode, path, traceMap) {
  1513. if (patternNode.type === "Identifier") {
  1514. const variable = findVariable(this.globalScope, patternNode);
  1515. if (variable != null) {
  1516. yield* this._iterateVariableReferences(
  1517. variable,
  1518. path,
  1519. traceMap,
  1520. false
  1521. );
  1522. }
  1523. return
  1524. }
  1525. if (patternNode.type === "ObjectPattern") {
  1526. for (const property of patternNode.properties) {
  1527. const key = getPropertyName(property);
  1528. if (key == null || !has(traceMap, key)) {
  1529. continue
  1530. }
  1531. const nextPath = path.concat(key);
  1532. const nextTraceMap = traceMap[key];
  1533. if (nextTraceMap[READ]) {
  1534. yield {
  1535. node: property,
  1536. path: nextPath,
  1537. type: READ,
  1538. info: nextTraceMap[READ],
  1539. };
  1540. }
  1541. yield* this._iterateLhsReferences(
  1542. property.value,
  1543. nextPath,
  1544. nextTraceMap
  1545. );
  1546. }
  1547. return
  1548. }
  1549. if (patternNode.type === "AssignmentPattern") {
  1550. yield* this._iterateLhsReferences(patternNode.left, path, traceMap);
  1551. }
  1552. }
  1553. /**
  1554. * Iterate the references for a given ModuleSpecifier node.
  1555. * @param {Node} specifierNode The ModuleSpecifier node to iterate references.
  1556. * @param {string[]} path The current path.
  1557. * @param {object} traceMap The trace map.
  1558. * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
  1559. */
  1560. *_iterateImportReferences(specifierNode, path, traceMap) {
  1561. const type = specifierNode.type;
  1562. if (type === "ImportSpecifier" || type === "ImportDefaultSpecifier") {
  1563. const key =
  1564. type === "ImportDefaultSpecifier"
  1565. ? "default"
  1566. : specifierNode.imported.name;
  1567. if (!has(traceMap, key)) {
  1568. return
  1569. }
  1570. path = path.concat(key); //eslint-disable-line no-param-reassign
  1571. const nextTraceMap = traceMap[key];
  1572. if (nextTraceMap[READ]) {
  1573. yield {
  1574. node: specifierNode,
  1575. path,
  1576. type: READ,
  1577. info: nextTraceMap[READ],
  1578. };
  1579. }
  1580. yield* this._iterateVariableReferences(
  1581. findVariable(this.globalScope, specifierNode.local),
  1582. path,
  1583. nextTraceMap,
  1584. false
  1585. );
  1586. return
  1587. }
  1588. if (type === "ImportNamespaceSpecifier") {
  1589. yield* this._iterateVariableReferences(
  1590. findVariable(this.globalScope, specifierNode.local),
  1591. path,
  1592. traceMap,
  1593. false
  1594. );
  1595. return
  1596. }
  1597. if (type === "ExportSpecifier") {
  1598. const key = specifierNode.local.name;
  1599. if (!has(traceMap, key)) {
  1600. return
  1601. }
  1602. path = path.concat(key); //eslint-disable-line no-param-reassign
  1603. const nextTraceMap = traceMap[key];
  1604. if (nextTraceMap[READ]) {
  1605. yield {
  1606. node: specifierNode,
  1607. path,
  1608. type: READ,
  1609. info: nextTraceMap[READ],
  1610. };
  1611. }
  1612. }
  1613. }
  1614. }
  1615. ReferenceTracker.READ = READ;
  1616. ReferenceTracker.CALL = CALL;
  1617. ReferenceTracker.CONSTRUCT = CONSTRUCT;
  1618. ReferenceTracker.ESM = ESM;
  1619. /**
  1620. * This is a predicate function for Array#filter.
  1621. * @param {string} name A name part.
  1622. * @param {number} index The index of the name.
  1623. * @returns {boolean} `false` if it's default.
  1624. */
  1625. function exceptDefault(name, index) {
  1626. return !(index === 1 && name === "default")
  1627. }
  1628. var index = {
  1629. CALL,
  1630. CONSTRUCT,
  1631. ESM,
  1632. findVariable,
  1633. getFunctionHeadLocation,
  1634. getFunctionNameWithKind,
  1635. getInnermostScope,
  1636. getPropertyName,
  1637. getStaticValue,
  1638. getStringIfConstant,
  1639. hasSideEffect,
  1640. isArrowToken,
  1641. isClosingBraceToken,
  1642. isClosingBracketToken,
  1643. isClosingParenToken,
  1644. isColonToken,
  1645. isCommaToken,
  1646. isCommentToken,
  1647. isNotArrowToken,
  1648. isNotClosingBraceToken,
  1649. isNotClosingBracketToken,
  1650. isNotClosingParenToken,
  1651. isNotColonToken,
  1652. isNotCommaToken,
  1653. isNotCommentToken,
  1654. isNotOpeningBraceToken,
  1655. isNotOpeningBracketToken,
  1656. isNotOpeningParenToken,
  1657. isNotSemicolonToken,
  1658. isOpeningBraceToken,
  1659. isOpeningBracketToken,
  1660. isOpeningParenToken,
  1661. isParenthesized,
  1662. isSemicolonToken,
  1663. PatternMatcher,
  1664. READ,
  1665. ReferenceTracker,
  1666. };
  1667. exports.CALL = CALL;
  1668. exports.CONSTRUCT = CONSTRUCT;
  1669. exports.ESM = ESM;
  1670. exports.PatternMatcher = PatternMatcher;
  1671. exports.READ = READ;
  1672. exports.ReferenceTracker = ReferenceTracker;
  1673. exports.default = index;
  1674. exports.findVariable = findVariable;
  1675. exports.getFunctionHeadLocation = getFunctionHeadLocation;
  1676. exports.getFunctionNameWithKind = getFunctionNameWithKind;
  1677. exports.getInnermostScope = getInnermostScope;
  1678. exports.getPropertyName = getPropertyName;
  1679. exports.getStaticValue = getStaticValue;
  1680. exports.getStringIfConstant = getStringIfConstant;
  1681. exports.hasSideEffect = hasSideEffect;
  1682. exports.isArrowToken = isArrowToken;
  1683. exports.isClosingBraceToken = isClosingBraceToken;
  1684. exports.isClosingBracketToken = isClosingBracketToken;
  1685. exports.isClosingParenToken = isClosingParenToken;
  1686. exports.isColonToken = isColonToken;
  1687. exports.isCommaToken = isCommaToken;
  1688. exports.isCommentToken = isCommentToken;
  1689. exports.isNotArrowToken = isNotArrowToken;
  1690. exports.isNotClosingBraceToken = isNotClosingBraceToken;
  1691. exports.isNotClosingBracketToken = isNotClosingBracketToken;
  1692. exports.isNotClosingParenToken = isNotClosingParenToken;
  1693. exports.isNotColonToken = isNotColonToken;
  1694. exports.isNotCommaToken = isNotCommaToken;
  1695. exports.isNotCommentToken = isNotCommentToken;
  1696. exports.isNotOpeningBraceToken = isNotOpeningBraceToken;
  1697. exports.isNotOpeningBracketToken = isNotOpeningBracketToken;
  1698. exports.isNotOpeningParenToken = isNotOpeningParenToken;
  1699. exports.isNotSemicolonToken = isNotSemicolonToken;
  1700. exports.isOpeningBraceToken = isOpeningBraceToken;
  1701. exports.isOpeningBracketToken = isOpeningBracketToken;
  1702. exports.isOpeningParenToken = isOpeningParenToken;
  1703. exports.isParenthesized = isParenthesized;
  1704. exports.isSemicolonToken = isSemicolonToken;
  1705. //# sourceMappingURL=index.js.map