index.mjs 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453
  1. import { getKeys, KEYS } from 'eslint-visitor-keys';
  2. /** @typedef {import("eslint").Scope.Scope} Scope */
  3. /** @typedef {import("estree").Node} Node */
  4. /**
  5. * Get the innermost scope which contains a given location.
  6. * @param {Scope} initialScope The initial scope to search.
  7. * @param {Node} node The location to search.
  8. * @returns {Scope} The innermost scope.
  9. */
  10. function getInnermostScope(initialScope, node) {
  11. const location = /** @type {[number, number]} */ (node.range)[0];
  12. let scope = initialScope;
  13. let found = false;
  14. do {
  15. found = false;
  16. for (const childScope of scope.childScopes) {
  17. const range = /** @type {[number, number]} */ (
  18. childScope.block.range
  19. );
  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. /** @typedef {import("eslint").Scope.Scope} Scope */
  30. /** @typedef {import("eslint").Scope.Variable} Variable */
  31. /** @typedef {import("estree").Identifier} Identifier */
  32. /**
  33. * Find the variable of a given name.
  34. * @param {Scope} initialScope The scope to start finding.
  35. * @param {string|Identifier} nameOrNode The variable name to find. If this is a Node object then it should be an Identifier node.
  36. * @returns {Variable|null} The found variable or null.
  37. */
  38. function findVariable(initialScope, nameOrNode) {
  39. let name = "";
  40. /** @type {Scope|null} */
  41. let scope = initialScope;
  42. if (typeof nameOrNode === "string") {
  43. name = nameOrNode;
  44. } else {
  45. name = nameOrNode.name;
  46. scope = getInnermostScope(scope, nameOrNode);
  47. }
  48. while (scope != null) {
  49. const variable = scope.set.get(name);
  50. if (variable != null) {
  51. return variable
  52. }
  53. scope = scope.upper;
  54. }
  55. return null
  56. }
  57. /** @typedef {import("eslint").AST.Token} Token */
  58. /** @typedef {import("estree").Comment} Comment */
  59. /** @typedef {import("./types.mjs").ArrowToken} ArrowToken */
  60. /** @typedef {import("./types.mjs").CommaToken} CommaToken */
  61. /** @typedef {import("./types.mjs").SemicolonToken} SemicolonToken */
  62. /** @typedef {import("./types.mjs").ColonToken} ColonToken */
  63. /** @typedef {import("./types.mjs").OpeningParenToken} OpeningParenToken */
  64. /** @typedef {import("./types.mjs").ClosingParenToken} ClosingParenToken */
  65. /** @typedef {import("./types.mjs").OpeningBracketToken} OpeningBracketToken */
  66. /** @typedef {import("./types.mjs").ClosingBracketToken} ClosingBracketToken */
  67. /** @typedef {import("./types.mjs").OpeningBraceToken} OpeningBraceToken */
  68. /** @typedef {import("./types.mjs").ClosingBraceToken} ClosingBraceToken */
  69. /**
  70. * @template {string} Value
  71. * @typedef {import("./types.mjs").PunctuatorToken<Value>} PunctuatorToken
  72. */
  73. /** @typedef {Comment | Token} CommentOrToken */
  74. /**
  75. * Creates the negate function of the given function.
  76. * @param {function(CommentOrToken):boolean} f - The function to negate.
  77. * @returns {function(CommentOrToken):boolean} Negated function.
  78. */
  79. function negate(f) {
  80. return (token) => !f(token)
  81. }
  82. /**
  83. * Checks if the given token is a PunctuatorToken with the given value
  84. * @template {string} Value
  85. * @param {CommentOrToken} token - The token to check.
  86. * @param {Value} value - The value to check.
  87. * @returns {token is PunctuatorToken<Value>} `true` if the token is a PunctuatorToken with the given value.
  88. */
  89. function isPunctuatorTokenWithValue(token, value) {
  90. return token.type === "Punctuator" && token.value === value
  91. }
  92. /**
  93. * Checks if the given token is an arrow token or not.
  94. * @param {CommentOrToken} token - The token to check.
  95. * @returns {token is ArrowToken} `true` if the token is an arrow token.
  96. */
  97. function isArrowToken(token) {
  98. return isPunctuatorTokenWithValue(token, "=>")
  99. }
  100. /**
  101. * Checks if the given token is a comma token or not.
  102. * @param {CommentOrToken} token - The token to check.
  103. * @returns {token is CommaToken} `true` if the token is a comma token.
  104. */
  105. function isCommaToken(token) {
  106. return isPunctuatorTokenWithValue(token, ",")
  107. }
  108. /**
  109. * Checks if the given token is a semicolon token or not.
  110. * @param {CommentOrToken} token - The token to check.
  111. * @returns {token is SemicolonToken} `true` if the token is a semicolon token.
  112. */
  113. function isSemicolonToken(token) {
  114. return isPunctuatorTokenWithValue(token, ";")
  115. }
  116. /**
  117. * Checks if the given token is a colon token or not.
  118. * @param {CommentOrToken} token - The token to check.
  119. * @returns {token is ColonToken} `true` if the token is a colon token.
  120. */
  121. function isColonToken(token) {
  122. return isPunctuatorTokenWithValue(token, ":")
  123. }
  124. /**
  125. * Checks if the given token is an opening parenthesis token or not.
  126. * @param {CommentOrToken} token - The token to check.
  127. * @returns {token is OpeningParenToken} `true` if the token is an opening parenthesis token.
  128. */
  129. function isOpeningParenToken(token) {
  130. return isPunctuatorTokenWithValue(token, "(")
  131. }
  132. /**
  133. * Checks if the given token is a closing parenthesis token or not.
  134. * @param {CommentOrToken} token - The token to check.
  135. * @returns {token is ClosingParenToken} `true` if the token is a closing parenthesis token.
  136. */
  137. function isClosingParenToken(token) {
  138. return isPunctuatorTokenWithValue(token, ")")
  139. }
  140. /**
  141. * Checks if the given token is an opening square bracket token or not.
  142. * @param {CommentOrToken} token - The token to check.
  143. * @returns {token is OpeningBracketToken} `true` if the token is an opening square bracket token.
  144. */
  145. function isOpeningBracketToken(token) {
  146. return isPunctuatorTokenWithValue(token, "[")
  147. }
  148. /**
  149. * Checks if the given token is a closing square bracket token or not.
  150. * @param {CommentOrToken} token - The token to check.
  151. * @returns {token is ClosingBracketToken} `true` if the token is a closing square bracket token.
  152. */
  153. function isClosingBracketToken(token) {
  154. return isPunctuatorTokenWithValue(token, "]")
  155. }
  156. /**
  157. * Checks if the given token is an opening brace token or not.
  158. * @param {CommentOrToken} token - The token to check.
  159. * @returns {token is OpeningBraceToken} `true` if the token is an opening brace token.
  160. */
  161. function isOpeningBraceToken(token) {
  162. return isPunctuatorTokenWithValue(token, "{")
  163. }
  164. /**
  165. * Checks if the given token is a closing brace token or not.
  166. * @param {CommentOrToken} token - The token to check.
  167. * @returns {token is ClosingBraceToken} `true` if the token is a closing brace token.
  168. */
  169. function isClosingBraceToken(token) {
  170. return isPunctuatorTokenWithValue(token, "}")
  171. }
  172. /**
  173. * Checks if the given token is a comment token or not.
  174. * @param {CommentOrToken} token - The token to check.
  175. * @returns {token is Comment} `true` if the token is a comment token.
  176. */
  177. function isCommentToken(token) {
  178. return ["Block", "Line", "Shebang"].includes(token.type)
  179. }
  180. const isNotArrowToken = negate(isArrowToken);
  181. const isNotCommaToken = negate(isCommaToken);
  182. const isNotSemicolonToken = negate(isSemicolonToken);
  183. const isNotColonToken = negate(isColonToken);
  184. const isNotOpeningParenToken = negate(isOpeningParenToken);
  185. const isNotClosingParenToken = negate(isClosingParenToken);
  186. const isNotOpeningBracketToken = negate(isOpeningBracketToken);
  187. const isNotClosingBracketToken = negate(isClosingBracketToken);
  188. const isNotOpeningBraceToken = negate(isOpeningBraceToken);
  189. const isNotClosingBraceToken = negate(isClosingBraceToken);
  190. const isNotCommentToken = negate(isCommentToken);
  191. /** @typedef {import("eslint").Rule.Node} RuleNode */
  192. /** @typedef {import("eslint").SourceCode} SourceCode */
  193. /** @typedef {import("eslint").AST.Token} Token */
  194. /** @typedef {import("estree").Function} FunctionNode */
  195. /** @typedef {import("estree").FunctionDeclaration} FunctionDeclaration */
  196. /** @typedef {import("estree").FunctionExpression} FunctionExpression */
  197. /** @typedef {import("estree").SourceLocation} SourceLocation */
  198. /** @typedef {import("estree").Position} Position */
  199. /**
  200. * Get the `(` token of the given function node.
  201. * @param {FunctionExpression | FunctionDeclaration} node - The function node to get.
  202. * @param {SourceCode} sourceCode - The source code object to get tokens.
  203. * @returns {Token} `(` token.
  204. */
  205. function getOpeningParenOfParams(node, sourceCode) {
  206. return node.id
  207. ? /** @type {Token} */ (
  208. sourceCode.getTokenAfter(node.id, isOpeningParenToken)
  209. )
  210. : /** @type {Token} */ (
  211. sourceCode.getFirstToken(node, isOpeningParenToken)
  212. )
  213. }
  214. /**
  215. * Get the location of the given function node for reporting.
  216. * @param {FunctionNode} node - The function node to get.
  217. * @param {SourceCode} sourceCode - The source code object to get tokens.
  218. * @returns {SourceLocation|null} The location of the function node for reporting.
  219. */
  220. function getFunctionHeadLocation(node, sourceCode) {
  221. const parent = /** @type {RuleNode} */ (node).parent;
  222. /** @type {Position|null} */
  223. let start = null;
  224. /** @type {Position|null} */
  225. let end = null;
  226. if (node.type === "ArrowFunctionExpression") {
  227. const arrowToken = /** @type {Token} */ (
  228. sourceCode.getTokenBefore(node.body, isArrowToken)
  229. );
  230. start = arrowToken.loc.start;
  231. end = arrowToken.loc.end;
  232. } else if (
  233. parent.type === "Property" ||
  234. parent.type === "MethodDefinition" ||
  235. parent.type === "PropertyDefinition"
  236. ) {
  237. start = /** @type {SourceLocation} */ (parent.loc).start;
  238. end = getOpeningParenOfParams(node, sourceCode).loc.start;
  239. } else {
  240. start = /** @type {SourceLocation} */ (node.loc).start;
  241. end = getOpeningParenOfParams(node, sourceCode).loc.start;
  242. }
  243. return {
  244. start: { ...start },
  245. end: { ...end },
  246. }
  247. }
  248. /* globals globalThis, global, self, window */
  249. /** @typedef {import("./types.mjs").StaticValue} StaticValue */
  250. /** @typedef {import("eslint").Scope.Scope} Scope */
  251. /** @typedef {import("estree").Node} Node */
  252. /** @typedef {import("@typescript-eslint/types").TSESTree.Node} TSESTreeNode */
  253. /** @typedef {import("@typescript-eslint/types").TSESTree.AST_NODE_TYPES} TSESTreeNodeTypes */
  254. /** @typedef {import("@typescript-eslint/types").TSESTree.MemberExpression} MemberExpression */
  255. /** @typedef {import("@typescript-eslint/types").TSESTree.Property} Property */
  256. /** @typedef {import("@typescript-eslint/types").TSESTree.RegExpLiteral} RegExpLiteral */
  257. /** @typedef {import("@typescript-eslint/types").TSESTree.BigIntLiteral} BigIntLiteral */
  258. /** @typedef {import("@typescript-eslint/types").TSESTree.Literal} Literal */
  259. const globalObject =
  260. typeof globalThis !== "undefined"
  261. ? globalThis
  262. : // @ts-ignore
  263. typeof self !== "undefined"
  264. ? // @ts-ignore
  265. self
  266. : // @ts-ignore
  267. typeof window !== "undefined"
  268. ? // @ts-ignore
  269. window
  270. : typeof global !== "undefined"
  271. ? global
  272. : {};
  273. const builtinNames = Object.freeze(
  274. new Set([
  275. "Array",
  276. "ArrayBuffer",
  277. "BigInt",
  278. "BigInt64Array",
  279. "BigUint64Array",
  280. "Boolean",
  281. "DataView",
  282. "Date",
  283. "decodeURI",
  284. "decodeURIComponent",
  285. "encodeURI",
  286. "encodeURIComponent",
  287. "escape",
  288. "Float32Array",
  289. "Float64Array",
  290. "Function",
  291. "Infinity",
  292. "Int16Array",
  293. "Int32Array",
  294. "Int8Array",
  295. "isFinite",
  296. "isNaN",
  297. "isPrototypeOf",
  298. "JSON",
  299. "Map",
  300. "Math",
  301. "NaN",
  302. "Number",
  303. "Object",
  304. "parseFloat",
  305. "parseInt",
  306. "Promise",
  307. "Proxy",
  308. "Reflect",
  309. "RegExp",
  310. "Set",
  311. "String",
  312. "Symbol",
  313. "Uint16Array",
  314. "Uint32Array",
  315. "Uint8Array",
  316. "Uint8ClampedArray",
  317. "undefined",
  318. "unescape",
  319. "WeakMap",
  320. "WeakSet",
  321. ]),
  322. );
  323. const callAllowed = new Set(
  324. [
  325. Array.isArray,
  326. Array.of,
  327. Array.prototype.at,
  328. Array.prototype.concat,
  329. Array.prototype.entries,
  330. Array.prototype.every,
  331. Array.prototype.filter,
  332. Array.prototype.find,
  333. Array.prototype.findIndex,
  334. Array.prototype.flat,
  335. Array.prototype.includes,
  336. Array.prototype.indexOf,
  337. Array.prototype.join,
  338. Array.prototype.keys,
  339. Array.prototype.lastIndexOf,
  340. Array.prototype.slice,
  341. Array.prototype.some,
  342. Array.prototype.toString,
  343. Array.prototype.values,
  344. typeof BigInt === "function" ? BigInt : undefined,
  345. Boolean,
  346. Date,
  347. Date.parse,
  348. decodeURI,
  349. decodeURIComponent,
  350. encodeURI,
  351. encodeURIComponent,
  352. escape,
  353. isFinite,
  354. isNaN,
  355. // @ts-ignore
  356. isPrototypeOf,
  357. Map,
  358. Map.prototype.entries,
  359. Map.prototype.get,
  360. Map.prototype.has,
  361. Map.prototype.keys,
  362. Map.prototype.values,
  363. .../** @type {(keyof typeof Math)[]} */ (
  364. Object.getOwnPropertyNames(Math)
  365. )
  366. .filter((k) => k !== "random")
  367. .map((k) => Math[k])
  368. .filter((f) => typeof f === "function"),
  369. Number,
  370. Number.isFinite,
  371. Number.isNaN,
  372. Number.parseFloat,
  373. Number.parseInt,
  374. Number.prototype.toExponential,
  375. Number.prototype.toFixed,
  376. Number.prototype.toPrecision,
  377. Number.prototype.toString,
  378. Object,
  379. Object.entries,
  380. Object.is,
  381. Object.isExtensible,
  382. Object.isFrozen,
  383. Object.isSealed,
  384. Object.keys,
  385. Object.values,
  386. parseFloat,
  387. parseInt,
  388. RegExp,
  389. Set,
  390. Set.prototype.entries,
  391. Set.prototype.has,
  392. Set.prototype.keys,
  393. Set.prototype.values,
  394. String,
  395. String.fromCharCode,
  396. String.fromCodePoint,
  397. String.raw,
  398. String.prototype.at,
  399. String.prototype.charAt,
  400. String.prototype.charCodeAt,
  401. String.prototype.codePointAt,
  402. String.prototype.concat,
  403. String.prototype.endsWith,
  404. String.prototype.includes,
  405. String.prototype.indexOf,
  406. String.prototype.lastIndexOf,
  407. String.prototype.normalize,
  408. String.prototype.padEnd,
  409. String.prototype.padStart,
  410. String.prototype.slice,
  411. String.prototype.startsWith,
  412. String.prototype.substr,
  413. String.prototype.substring,
  414. String.prototype.toLowerCase,
  415. String.prototype.toString,
  416. String.prototype.toUpperCase,
  417. String.prototype.trim,
  418. String.prototype.trimEnd,
  419. String.prototype.trimLeft,
  420. String.prototype.trimRight,
  421. String.prototype.trimStart,
  422. Symbol.for,
  423. Symbol.keyFor,
  424. unescape,
  425. ].filter((f) => typeof f === "function"),
  426. );
  427. const callPassThrough = new Set([
  428. Object.freeze,
  429. Object.preventExtensions,
  430. Object.seal,
  431. ]);
  432. /** @type {ReadonlyArray<readonly [Function, ReadonlySet<string>]>} */
  433. const getterAllowed = [
  434. [Map, new Set(["size"])],
  435. [
  436. RegExp,
  437. new Set([
  438. "dotAll",
  439. "flags",
  440. "global",
  441. "hasIndices",
  442. "ignoreCase",
  443. "multiline",
  444. "source",
  445. "sticky",
  446. "unicode",
  447. ]),
  448. ],
  449. [Set, new Set(["size"])],
  450. ];
  451. /**
  452. * Get the property descriptor.
  453. * @param {object} object The object to get.
  454. * @param {string|number|symbol} name The property name to get.
  455. */
  456. function getPropertyDescriptor(object, name) {
  457. let x = object;
  458. while ((typeof x === "object" || typeof x === "function") && x !== null) {
  459. const d = Object.getOwnPropertyDescriptor(x, name);
  460. if (d) {
  461. return d
  462. }
  463. x = Object.getPrototypeOf(x);
  464. }
  465. return null
  466. }
  467. /**
  468. * Check if a property is getter or not.
  469. * @param {object} object The object to check.
  470. * @param {string|number|symbol} name The property name to check.
  471. */
  472. function isGetter(object, name) {
  473. const d = getPropertyDescriptor(object, name);
  474. return d != null && d.get != null
  475. }
  476. /**
  477. * Get the element values of a given node list.
  478. * @param {(Node|TSESTreeNode|null)[]} nodeList The node list to get values.
  479. * @param {Scope|undefined|null} initialScope The initial scope to find variables.
  480. * @returns {any[]|null} The value list if all nodes are constant. Otherwise, null.
  481. */
  482. function getElementValues(nodeList, initialScope) {
  483. const valueList = [];
  484. for (let i = 0; i < nodeList.length; ++i) {
  485. const elementNode = nodeList[i];
  486. if (elementNode == null) {
  487. valueList.length = i + 1;
  488. } else if (elementNode.type === "SpreadElement") {
  489. const argument = getStaticValueR(elementNode.argument, initialScope);
  490. if (argument == null) {
  491. return null
  492. }
  493. valueList.push(.../** @type {Iterable<any>} */ (argument.value));
  494. } else {
  495. const element = getStaticValueR(elementNode, initialScope);
  496. if (element == null) {
  497. return null
  498. }
  499. valueList.push(element.value);
  500. }
  501. }
  502. return valueList
  503. }
  504. /**
  505. * Returns whether the given variable is never written to after initialization.
  506. * @param {import("eslint").Scope.Variable} variable
  507. * @returns {boolean}
  508. */
  509. function isEffectivelyConst(variable) {
  510. const refs = variable.references;
  511. const inits = refs.filter((r) => r.init).length;
  512. const reads = refs.filter((r) => r.isReadOnly()).length;
  513. if (inits === 1 && reads + inits === refs.length) {
  514. // there is only one init and all other references only read
  515. return true
  516. }
  517. return false
  518. }
  519. /**
  520. * @template {TSESTreeNodeTypes} T
  521. * @callback VisitorCallback
  522. * @param {TSESTreeNode & { type: T }} node
  523. * @param {Scope|undefined|null} initialScope
  524. * @returns {StaticValue | null}
  525. */
  526. /**
  527. * @typedef { { [K in TSESTreeNodeTypes]?: VisitorCallback<K> } } Operations
  528. */
  529. /**
  530. * @type {Operations}
  531. */
  532. const operations = Object.freeze({
  533. ArrayExpression(node, initialScope) {
  534. const elements = getElementValues(node.elements, initialScope);
  535. return elements != null ? { value: elements } : null
  536. },
  537. AssignmentExpression(node, initialScope) {
  538. if (node.operator === "=") {
  539. return getStaticValueR(node.right, initialScope)
  540. }
  541. return null
  542. },
  543. //eslint-disable-next-line complexity
  544. BinaryExpression(node, initialScope) {
  545. if (node.operator === "in" || node.operator === "instanceof") {
  546. // Not supported.
  547. return null
  548. }
  549. const left = getStaticValueR(node.left, initialScope);
  550. const right = getStaticValueR(node.right, initialScope);
  551. if (left != null && right != null) {
  552. switch (node.operator) {
  553. case "==":
  554. return { value: left.value == right.value } //eslint-disable-line eqeqeq
  555. case "!=":
  556. return { value: left.value != right.value } //eslint-disable-line eqeqeq
  557. case "===":
  558. return { value: left.value === right.value }
  559. case "!==":
  560. return { value: left.value !== right.value }
  561. case "<":
  562. return {
  563. value:
  564. /** @type {any} */ (left.value) <
  565. /** @type {any} */ (right.value),
  566. }
  567. case "<=":
  568. return {
  569. value:
  570. /** @type {any} */ (left.value) <=
  571. /** @type {any} */ (right.value),
  572. }
  573. case ">":
  574. return {
  575. value:
  576. /** @type {any} */ (left.value) >
  577. /** @type {any} */ (right.value),
  578. }
  579. case ">=":
  580. return {
  581. value:
  582. /** @type {any} */ (left.value) >=
  583. /** @type {any} */ (right.value),
  584. }
  585. case "<<":
  586. return {
  587. value:
  588. /** @type {any} */ (left.value) <<
  589. /** @type {any} */ (right.value),
  590. }
  591. case ">>":
  592. return {
  593. value:
  594. /** @type {any} */ (left.value) >>
  595. /** @type {any} */ (right.value),
  596. }
  597. case ">>>":
  598. return {
  599. value:
  600. /** @type {any} */ (left.value) >>>
  601. /** @type {any} */ (right.value),
  602. }
  603. case "+":
  604. return {
  605. value:
  606. /** @type {any} */ (left.value) +
  607. /** @type {any} */ (right.value),
  608. }
  609. case "-":
  610. return {
  611. value:
  612. /** @type {any} */ (left.value) -
  613. /** @type {any} */ (right.value),
  614. }
  615. case "*":
  616. return {
  617. value:
  618. /** @type {any} */ (left.value) *
  619. /** @type {any} */ (right.value),
  620. }
  621. case "/":
  622. return {
  623. value:
  624. /** @type {any} */ (left.value) /
  625. /** @type {any} */ (right.value),
  626. }
  627. case "%":
  628. return {
  629. value:
  630. /** @type {any} */ (left.value) %
  631. /** @type {any} */ (right.value),
  632. }
  633. case "**":
  634. return {
  635. value:
  636. /** @type {any} */ (left.value) **
  637. /** @type {any} */ (right.value),
  638. }
  639. case "|":
  640. return {
  641. value:
  642. /** @type {any} */ (left.value) |
  643. /** @type {any} */ (right.value),
  644. }
  645. case "^":
  646. return {
  647. value:
  648. /** @type {any} */ (left.value) ^
  649. /** @type {any} */ (right.value),
  650. }
  651. case "&":
  652. return {
  653. value:
  654. /** @type {any} */ (left.value) &
  655. /** @type {any} */ (right.value),
  656. }
  657. // no default
  658. }
  659. }
  660. return null
  661. },
  662. CallExpression(node, initialScope) {
  663. const calleeNode = node.callee;
  664. const args = getElementValues(node.arguments, initialScope);
  665. if (args != null) {
  666. if (calleeNode.type === "MemberExpression") {
  667. if (calleeNode.property.type === "PrivateIdentifier") {
  668. return null
  669. }
  670. const object = getStaticValueR(calleeNode.object, initialScope);
  671. if (object != null) {
  672. if (
  673. object.value == null &&
  674. (object.optional || node.optional)
  675. ) {
  676. return { value: undefined, optional: true }
  677. }
  678. const property = getStaticPropertyNameValue(
  679. calleeNode,
  680. initialScope,
  681. );
  682. if (property != null) {
  683. const receiver =
  684. /** @type {Record<PropertyKey, (...args: any[]) => any>} */ (
  685. object.value
  686. );
  687. const methodName = /** @type {PropertyKey} */ (
  688. property.value
  689. );
  690. if (callAllowed.has(receiver[methodName])) {
  691. return {
  692. value: receiver[methodName](...args),
  693. }
  694. }
  695. if (callPassThrough.has(receiver[methodName])) {
  696. return { value: args[0] }
  697. }
  698. }
  699. }
  700. } else {
  701. const callee = getStaticValueR(calleeNode, initialScope);
  702. if (callee != null) {
  703. if (callee.value == null && node.optional) {
  704. return { value: undefined, optional: true }
  705. }
  706. const func = /** @type {(...args: any[]) => any} */ (
  707. callee.value
  708. );
  709. if (callAllowed.has(func)) {
  710. return { value: func(...args) }
  711. }
  712. if (callPassThrough.has(func)) {
  713. return { value: args[0] }
  714. }
  715. }
  716. }
  717. }
  718. return null
  719. },
  720. ConditionalExpression(node, initialScope) {
  721. const test = getStaticValueR(node.test, initialScope);
  722. if (test != null) {
  723. return test.value
  724. ? getStaticValueR(node.consequent, initialScope)
  725. : getStaticValueR(node.alternate, initialScope)
  726. }
  727. return null
  728. },
  729. ExpressionStatement(node, initialScope) {
  730. return getStaticValueR(node.expression, initialScope)
  731. },
  732. Identifier(node, initialScope) {
  733. if (initialScope != null) {
  734. const variable = findVariable(initialScope, node);
  735. // Built-in globals.
  736. if (
  737. variable != null &&
  738. variable.defs.length === 0 &&
  739. builtinNames.has(variable.name) &&
  740. variable.name in globalObject
  741. ) {
  742. return { value: globalObject[variable.name] }
  743. }
  744. // Constants.
  745. if (variable != null && variable.defs.length === 1) {
  746. const def = variable.defs[0];
  747. if (
  748. def.parent &&
  749. def.type === "Variable" &&
  750. (def.parent.kind === "const" ||
  751. isEffectivelyConst(variable)) &&
  752. // TODO(mysticatea): don't support destructuring here.
  753. def.node.id.type === "Identifier"
  754. ) {
  755. return getStaticValueR(def.node.init, initialScope)
  756. }
  757. }
  758. }
  759. return null
  760. },
  761. Literal(node) {
  762. const literal =
  763. /** @type {Partial<Literal> & Partial<RegExpLiteral> & Partial<BigIntLiteral>} */ (
  764. node
  765. );
  766. //istanbul ignore if : this is implementation-specific behavior.
  767. if (
  768. (literal.regex != null || literal.bigint != null) &&
  769. literal.value == null
  770. ) {
  771. // It was a RegExp/BigInt literal, but Node.js didn't support it.
  772. return null
  773. }
  774. return { value: literal.value }
  775. },
  776. LogicalExpression(node, initialScope) {
  777. const left = getStaticValueR(node.left, initialScope);
  778. if (left != null) {
  779. if (
  780. (node.operator === "||" && Boolean(left.value) === true) ||
  781. (node.operator === "&&" && Boolean(left.value) === false) ||
  782. (node.operator === "??" && left.value != null)
  783. ) {
  784. return left
  785. }
  786. const right = getStaticValueR(node.right, initialScope);
  787. if (right != null) {
  788. return right
  789. }
  790. }
  791. return null
  792. },
  793. MemberExpression(node, initialScope) {
  794. if (node.property.type === "PrivateIdentifier") {
  795. return null
  796. }
  797. const object = getStaticValueR(node.object, initialScope);
  798. if (object != null) {
  799. if (object.value == null && (object.optional || node.optional)) {
  800. return { value: undefined, optional: true }
  801. }
  802. const property = getStaticPropertyNameValue(node, initialScope);
  803. if (property != null) {
  804. if (
  805. !isGetter(
  806. /** @type {object} */ (object.value),
  807. /** @type {PropertyKey} */ (property.value),
  808. )
  809. ) {
  810. return {
  811. value: /** @type {Record<PropertyKey, unknown>} */ (
  812. object.value
  813. )[/** @type {PropertyKey} */ (property.value)],
  814. }
  815. }
  816. for (const [classFn, allowed] of getterAllowed) {
  817. if (
  818. object.value instanceof classFn &&
  819. allowed.has(/** @type {string} */ (property.value))
  820. ) {
  821. return {
  822. value: /** @type {Record<PropertyKey, unknown>} */ (
  823. object.value
  824. )[/** @type {PropertyKey} */ (property.value)],
  825. }
  826. }
  827. }
  828. }
  829. }
  830. return null
  831. },
  832. ChainExpression(node, initialScope) {
  833. const expression = getStaticValueR(node.expression, initialScope);
  834. if (expression != null) {
  835. return { value: expression.value }
  836. }
  837. return null
  838. },
  839. NewExpression(node, initialScope) {
  840. const callee = getStaticValueR(node.callee, initialScope);
  841. const args = getElementValues(node.arguments, initialScope);
  842. if (callee != null && args != null) {
  843. const Func = /** @type {new (...args: any[]) => any} */ (
  844. callee.value
  845. );
  846. if (callAllowed.has(Func)) {
  847. return { value: new Func(...args) }
  848. }
  849. }
  850. return null
  851. },
  852. ObjectExpression(node, initialScope) {
  853. /** @type {Record<PropertyKey, unknown>} */
  854. const object = {};
  855. for (const propertyNode of node.properties) {
  856. if (propertyNode.type === "Property") {
  857. if (propertyNode.kind !== "init") {
  858. return null
  859. }
  860. const key = getStaticPropertyNameValue(
  861. propertyNode,
  862. initialScope,
  863. );
  864. const value = getStaticValueR(propertyNode.value, initialScope);
  865. if (key == null || value == null) {
  866. return null
  867. }
  868. object[/** @type {PropertyKey} */ (key.value)] = value.value;
  869. } else if (
  870. propertyNode.type === "SpreadElement" ||
  871. // @ts-expect-error -- Backward compatibility
  872. propertyNode.type === "ExperimentalSpreadProperty"
  873. ) {
  874. const argument = getStaticValueR(
  875. propertyNode.argument,
  876. initialScope,
  877. );
  878. if (argument == null) {
  879. return null
  880. }
  881. Object.assign(object, argument.value);
  882. } else {
  883. return null
  884. }
  885. }
  886. return { value: object }
  887. },
  888. SequenceExpression(node, initialScope) {
  889. const last = node.expressions[node.expressions.length - 1];
  890. return getStaticValueR(last, initialScope)
  891. },
  892. TaggedTemplateExpression(node, initialScope) {
  893. const tag = getStaticValueR(node.tag, initialScope);
  894. const expressions = getElementValues(
  895. node.quasi.expressions,
  896. initialScope,
  897. );
  898. if (tag != null && expressions != null) {
  899. const func = /** @type {(...args: any[]) => any} */ (tag.value);
  900. /** @type {any[] & { raw?: string[] }} */
  901. const strings = node.quasi.quasis.map((q) => q.value.cooked);
  902. strings.raw = node.quasi.quasis.map((q) => q.value.raw);
  903. if (func === String.raw) {
  904. return { value: func(strings, ...expressions) }
  905. }
  906. }
  907. return null
  908. },
  909. TemplateLiteral(node, initialScope) {
  910. const expressions = getElementValues(node.expressions, initialScope);
  911. if (expressions != null) {
  912. let value = node.quasis[0].value.cooked;
  913. for (let i = 0; i < expressions.length; ++i) {
  914. value += expressions[i];
  915. value += /** @type {string} */ (node.quasis[i + 1].value.cooked);
  916. }
  917. return { value }
  918. }
  919. return null
  920. },
  921. UnaryExpression(node, initialScope) {
  922. if (node.operator === "delete") {
  923. // Not supported.
  924. return null
  925. }
  926. if (node.operator === "void") {
  927. return { value: undefined }
  928. }
  929. const arg = getStaticValueR(node.argument, initialScope);
  930. if (arg != null) {
  931. switch (node.operator) {
  932. case "-":
  933. return { value: -(/** @type {any} */ (arg.value)) }
  934. case "+":
  935. return { value: +(/** @type {any} */ (arg.value)) } //eslint-disable-line no-implicit-coercion
  936. case "!":
  937. return { value: !arg.value }
  938. case "~":
  939. return { value: ~(/** @type {any} */ (arg.value)) }
  940. case "typeof":
  941. return { value: typeof arg.value }
  942. // no default
  943. }
  944. }
  945. return null
  946. },
  947. TSAsExpression(node, initialScope) {
  948. return getStaticValueR(node.expression, initialScope)
  949. },
  950. TSSatisfiesExpression(node, initialScope) {
  951. return getStaticValueR(node.expression, initialScope)
  952. },
  953. TSTypeAssertion(node, initialScope) {
  954. return getStaticValueR(node.expression, initialScope)
  955. },
  956. TSNonNullExpression(node, initialScope) {
  957. return getStaticValueR(node.expression, initialScope)
  958. },
  959. TSInstantiationExpression(node, initialScope) {
  960. return getStaticValueR(node.expression, initialScope)
  961. },
  962. });
  963. /**
  964. * Get the value of a given node if it's a static value.
  965. * @param {Node|TSESTreeNode|null|undefined} node The node to get.
  966. * @param {Scope|undefined|null} initialScope The scope to start finding variable.
  967. * @returns {StaticValue|null} The static value of the node, or `null`.
  968. */
  969. function getStaticValueR(node, initialScope) {
  970. if (node != null && Object.hasOwnProperty.call(operations, node.type)) {
  971. return /** @type {VisitorCallback<any>} */ (operations[node.type])(
  972. /** @type {TSESTreeNode} */ (node),
  973. initialScope,
  974. )
  975. }
  976. return null
  977. }
  978. /**
  979. * Get the static value of property name from a MemberExpression node or a Property node.
  980. * @param {MemberExpression|Property} node The node to get.
  981. * @param {Scope|null} [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.
  982. * @returns {StaticValue|null} The static value of the property name of the node, or `null`.
  983. */
  984. function getStaticPropertyNameValue(node, initialScope) {
  985. const nameNode = node.type === "Property" ? node.key : node.property;
  986. if (node.computed) {
  987. return getStaticValueR(nameNode, initialScope)
  988. }
  989. if (nameNode.type === "Identifier") {
  990. return { value: nameNode.name }
  991. }
  992. if (nameNode.type === "Literal") {
  993. if (/** @type {Partial<BigIntLiteral>} */ (nameNode).bigint) {
  994. return { value: /** @type {BigIntLiteral} */ (nameNode).bigint }
  995. }
  996. return { value: String(nameNode.value) }
  997. }
  998. return null
  999. }
  1000. /**
  1001. * Get the value of a given node if it's a static value.
  1002. * @param {Node} node The node to get.
  1003. * @param {Scope|null} [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.
  1004. * @returns {StaticValue | null} The static value of the node, or `null`.
  1005. */
  1006. function getStaticValue(node, initialScope = null) {
  1007. try {
  1008. return getStaticValueR(node, initialScope)
  1009. } catch (_error) {
  1010. return null
  1011. }
  1012. }
  1013. /** @typedef {import("eslint").Scope.Scope} Scope */
  1014. /** @typedef {import("estree").Node} Node */
  1015. /** @typedef {import("estree").RegExpLiteral} RegExpLiteral */
  1016. /** @typedef {import("estree").BigIntLiteral} BigIntLiteral */
  1017. /** @typedef {import("estree").SimpleLiteral} SimpleLiteral */
  1018. /**
  1019. * Get the value of a given node if it's a literal or a template literal.
  1020. * @param {Node} node The node to get.
  1021. * @param {Scope|null} [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.
  1022. * @returns {string|null} The value of the node, or `null`.
  1023. */
  1024. function getStringIfConstant(node, initialScope = null) {
  1025. // Handle the literals that the platform doesn't support natively.
  1026. if (node && node.type === "Literal" && node.value === null) {
  1027. const literal =
  1028. /** @type {Partial<SimpleLiteral> & Partial<RegExpLiteral> & Partial<BigIntLiteral>} */ (
  1029. node
  1030. );
  1031. if (literal.regex) {
  1032. return `/${literal.regex.pattern}/${literal.regex.flags}`
  1033. }
  1034. if (literal.bigint) {
  1035. return literal.bigint
  1036. }
  1037. }
  1038. const evaluated = getStaticValue(node, initialScope);
  1039. if (evaluated) {
  1040. // `String(Symbol.prototype)` throws error
  1041. try {
  1042. return String(evaluated.value)
  1043. } catch {
  1044. // No op
  1045. }
  1046. }
  1047. return null
  1048. }
  1049. /** @typedef {import("eslint").Scope.Scope} Scope */
  1050. /** @typedef {import("estree").MemberExpression} MemberExpression */
  1051. /** @typedef {import("estree").MethodDefinition} MethodDefinition */
  1052. /** @typedef {import("estree").Property} Property */
  1053. /** @typedef {import("estree").PropertyDefinition} PropertyDefinition */
  1054. /** @typedef {import("estree").Identifier} Identifier */
  1055. /**
  1056. * Get the property name from a MemberExpression node or a Property node.
  1057. * @param {MemberExpression | MethodDefinition | Property | PropertyDefinition} node The node to get.
  1058. * @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.
  1059. * @returns {string|null|undefined} The property name of the node.
  1060. */
  1061. function getPropertyName(node, initialScope) {
  1062. switch (node.type) {
  1063. case "MemberExpression":
  1064. if (node.computed) {
  1065. return getStringIfConstant(node.property, initialScope)
  1066. }
  1067. if (node.property.type === "PrivateIdentifier") {
  1068. return null
  1069. }
  1070. return /** @type {Partial<Identifier>} */ (node.property).name
  1071. case "Property":
  1072. case "MethodDefinition":
  1073. case "PropertyDefinition":
  1074. if (node.computed) {
  1075. return getStringIfConstant(node.key, initialScope)
  1076. }
  1077. if (node.key.type === "Literal") {
  1078. return String(node.key.value)
  1079. }
  1080. if (node.key.type === "PrivateIdentifier") {
  1081. return null
  1082. }
  1083. return /** @type {Partial<Identifier>} */ (node.key).name
  1084. }
  1085. return null
  1086. }
  1087. /** @typedef {import("eslint").Rule.Node} RuleNode */
  1088. /** @typedef {import("eslint").SourceCode} SourceCode */
  1089. /** @typedef {import("estree").Function} FunctionNode */
  1090. /** @typedef {import("estree").FunctionDeclaration} FunctionDeclaration */
  1091. /** @typedef {import("estree").FunctionExpression} FunctionExpression */
  1092. /** @typedef {import("estree").Identifier} Identifier */
  1093. /**
  1094. * Get the name and kind of the given function node.
  1095. * @param {FunctionNode} node - The function node to get.
  1096. * @param {SourceCode} [sourceCode] The source code object to get the code of computed property keys.
  1097. * @returns {string} The name and kind of the function node.
  1098. */
  1099. // eslint-disable-next-line complexity
  1100. function getFunctionNameWithKind(node, sourceCode) {
  1101. const parent = /** @type {RuleNode} */ (node).parent;
  1102. const tokens = [];
  1103. const isObjectMethod = parent.type === "Property" && parent.value === node;
  1104. const isClassMethod =
  1105. parent.type === "MethodDefinition" && parent.value === node;
  1106. const isClassFieldMethod =
  1107. parent.type === "PropertyDefinition" && parent.value === node;
  1108. // Modifiers.
  1109. if (isClassMethod || isClassFieldMethod) {
  1110. if (parent.static) {
  1111. tokens.push("static");
  1112. }
  1113. if (parent.key.type === "PrivateIdentifier") {
  1114. tokens.push("private");
  1115. }
  1116. }
  1117. if (node.async) {
  1118. tokens.push("async");
  1119. }
  1120. if (node.generator) {
  1121. tokens.push("generator");
  1122. }
  1123. // Kinds.
  1124. if (isObjectMethod || isClassMethod) {
  1125. if (parent.kind === "constructor") {
  1126. return "constructor"
  1127. }
  1128. if (parent.kind === "get") {
  1129. tokens.push("getter");
  1130. } else if (parent.kind === "set") {
  1131. tokens.push("setter");
  1132. } else {
  1133. tokens.push("method");
  1134. }
  1135. } else if (isClassFieldMethod) {
  1136. tokens.push("method");
  1137. } else {
  1138. if (node.type === "ArrowFunctionExpression") {
  1139. tokens.push("arrow");
  1140. }
  1141. tokens.push("function");
  1142. }
  1143. // Names.
  1144. if (isObjectMethod || isClassMethod || isClassFieldMethod) {
  1145. if (parent.key.type === "PrivateIdentifier") {
  1146. tokens.push(`#${parent.key.name}`);
  1147. } else {
  1148. const name = getPropertyName(parent);
  1149. if (name) {
  1150. tokens.push(`'${name}'`);
  1151. } else if (sourceCode) {
  1152. const keyText = sourceCode.getText(parent.key);
  1153. if (!keyText.includes("\n")) {
  1154. tokens.push(`[${keyText}]`);
  1155. }
  1156. }
  1157. }
  1158. } else if (hasId(node)) {
  1159. tokens.push(`'${node.id.name}'`);
  1160. } else if (
  1161. parent.type === "VariableDeclarator" &&
  1162. parent.id &&
  1163. parent.id.type === "Identifier"
  1164. ) {
  1165. tokens.push(`'${parent.id.name}'`);
  1166. } else if (
  1167. (parent.type === "AssignmentExpression" ||
  1168. parent.type === "AssignmentPattern") &&
  1169. parent.left &&
  1170. parent.left.type === "Identifier"
  1171. ) {
  1172. tokens.push(`'${parent.left.name}'`);
  1173. } else if (
  1174. parent.type === "ExportDefaultDeclaration" &&
  1175. parent.declaration === node
  1176. ) {
  1177. tokens.push("'default'");
  1178. }
  1179. return tokens.join(" ")
  1180. }
  1181. /**
  1182. * @param {FunctionNode} node
  1183. * @returns {node is FunctionDeclaration | FunctionExpression & { id: Identifier }}
  1184. */
  1185. function hasId(node) {
  1186. return Boolean(
  1187. /** @type {Partial<FunctionDeclaration | FunctionExpression>} */ (node)
  1188. .id,
  1189. )
  1190. }
  1191. /** @typedef {import("estree").Node} Node */
  1192. /** @typedef {import("eslint").SourceCode} SourceCode */
  1193. /** @typedef {import("./types.mjs").HasSideEffectOptions} HasSideEffectOptions */
  1194. /** @typedef {import("estree").BinaryExpression} BinaryExpression */
  1195. /** @typedef {import("estree").MemberExpression} MemberExpression */
  1196. /** @typedef {import("estree").MethodDefinition} MethodDefinition */
  1197. /** @typedef {import("estree").Property} Property */
  1198. /** @typedef {import("estree").PropertyDefinition} PropertyDefinition */
  1199. /** @typedef {import("estree").UnaryExpression} UnaryExpression */
  1200. const typeConversionBinaryOps = Object.freeze(
  1201. new Set([
  1202. "==",
  1203. "!=",
  1204. "<",
  1205. "<=",
  1206. ">",
  1207. ">=",
  1208. "<<",
  1209. ">>",
  1210. ">>>",
  1211. "+",
  1212. "-",
  1213. "*",
  1214. "/",
  1215. "%",
  1216. "|",
  1217. "^",
  1218. "&",
  1219. "in",
  1220. ]),
  1221. );
  1222. const typeConversionUnaryOps = Object.freeze(new Set(["-", "+", "!", "~"]));
  1223. /**
  1224. * Check whether the given value is an ASTNode or not.
  1225. * @param {any} x The value to check.
  1226. * @returns {x is Node} `true` if the value is an ASTNode.
  1227. */
  1228. function isNode(x) {
  1229. return x !== null && typeof x === "object" && typeof x.type === "string"
  1230. }
  1231. const visitor = Object.freeze(
  1232. Object.assign(Object.create(null), {
  1233. /**
  1234. * @param {Node} node
  1235. * @param {HasSideEffectOptions} options
  1236. * @param {Record<string, string[]>} visitorKeys
  1237. */
  1238. $visit(node, options, visitorKeys) {
  1239. const { type } = node;
  1240. if (typeof (/** @type {any} */ (this)[type]) === "function") {
  1241. return /** @type {any} */ (this)[type](
  1242. node,
  1243. options,
  1244. visitorKeys,
  1245. )
  1246. }
  1247. return this.$visitChildren(node, options, visitorKeys)
  1248. },
  1249. /**
  1250. * @param {Node} node
  1251. * @param {HasSideEffectOptions} options
  1252. * @param {Record<string, string[]>} visitorKeys
  1253. */
  1254. $visitChildren(node, options, visitorKeys) {
  1255. const { type } = node;
  1256. for (const key of /** @type {(keyof Node)[]} */ (
  1257. visitorKeys[type] || getKeys(node)
  1258. )) {
  1259. const value = node[key];
  1260. if (Array.isArray(value)) {
  1261. for (const element of value) {
  1262. if (
  1263. isNode(element) &&
  1264. this.$visit(element, options, visitorKeys)
  1265. ) {
  1266. return true
  1267. }
  1268. }
  1269. } else if (
  1270. isNode(value) &&
  1271. this.$visit(value, options, visitorKeys)
  1272. ) {
  1273. return true
  1274. }
  1275. }
  1276. return false
  1277. },
  1278. ArrowFunctionExpression() {
  1279. return false
  1280. },
  1281. AssignmentExpression() {
  1282. return true
  1283. },
  1284. AwaitExpression() {
  1285. return true
  1286. },
  1287. /**
  1288. * @param {BinaryExpression} node
  1289. * @param {HasSideEffectOptions} options
  1290. * @param {Record<string, string[]>} visitorKeys
  1291. */
  1292. BinaryExpression(node, options, visitorKeys) {
  1293. if (
  1294. options.considerImplicitTypeConversion &&
  1295. typeConversionBinaryOps.has(node.operator) &&
  1296. (node.left.type !== "Literal" || node.right.type !== "Literal")
  1297. ) {
  1298. return true
  1299. }
  1300. return this.$visitChildren(node, options, visitorKeys)
  1301. },
  1302. CallExpression() {
  1303. return true
  1304. },
  1305. FunctionExpression() {
  1306. return false
  1307. },
  1308. ImportExpression() {
  1309. return true
  1310. },
  1311. /**
  1312. * @param {MemberExpression} node
  1313. * @param {HasSideEffectOptions} options
  1314. * @param {Record<string, string[]>} visitorKeys
  1315. */
  1316. MemberExpression(node, options, visitorKeys) {
  1317. if (options.considerGetters) {
  1318. return true
  1319. }
  1320. if (
  1321. options.considerImplicitTypeConversion &&
  1322. node.computed &&
  1323. node.property.type !== "Literal"
  1324. ) {
  1325. return true
  1326. }
  1327. return this.$visitChildren(node, options, visitorKeys)
  1328. },
  1329. /**
  1330. * @param {MethodDefinition} node
  1331. * @param {HasSideEffectOptions} options
  1332. * @param {Record<string, string[]>} visitorKeys
  1333. */
  1334. MethodDefinition(node, options, visitorKeys) {
  1335. if (
  1336. options.considerImplicitTypeConversion &&
  1337. node.computed &&
  1338. node.key.type !== "Literal"
  1339. ) {
  1340. return true
  1341. }
  1342. return this.$visitChildren(node, options, visitorKeys)
  1343. },
  1344. NewExpression() {
  1345. return true
  1346. },
  1347. /**
  1348. * @param {Property} node
  1349. * @param {HasSideEffectOptions} options
  1350. * @param {Record<string, string[]>} visitorKeys
  1351. */
  1352. Property(node, options, visitorKeys) {
  1353. if (
  1354. options.considerImplicitTypeConversion &&
  1355. node.computed &&
  1356. node.key.type !== "Literal"
  1357. ) {
  1358. return true
  1359. }
  1360. return this.$visitChildren(node, options, visitorKeys)
  1361. },
  1362. /**
  1363. * @param {PropertyDefinition} node
  1364. * @param {HasSideEffectOptions} options
  1365. * @param {Record<string, string[]>} visitorKeys
  1366. */
  1367. PropertyDefinition(node, options, visitorKeys) {
  1368. if (
  1369. options.considerImplicitTypeConversion &&
  1370. node.computed &&
  1371. node.key.type !== "Literal"
  1372. ) {
  1373. return true
  1374. }
  1375. return this.$visitChildren(node, options, visitorKeys)
  1376. },
  1377. /**
  1378. * @param {UnaryExpression} node
  1379. * @param {HasSideEffectOptions} options
  1380. * @param {Record<string, string[]>} visitorKeys
  1381. */
  1382. UnaryExpression(node, options, visitorKeys) {
  1383. if (node.operator === "delete") {
  1384. return true
  1385. }
  1386. if (
  1387. options.considerImplicitTypeConversion &&
  1388. typeConversionUnaryOps.has(node.operator) &&
  1389. node.argument.type !== "Literal"
  1390. ) {
  1391. return true
  1392. }
  1393. return this.$visitChildren(node, options, visitorKeys)
  1394. },
  1395. UpdateExpression() {
  1396. return true
  1397. },
  1398. YieldExpression() {
  1399. return true
  1400. },
  1401. }),
  1402. );
  1403. /**
  1404. * Check whether a given node has any side effect or not.
  1405. * @param {Node} node The node to get.
  1406. * @param {SourceCode} sourceCode The source code object.
  1407. * @param {HasSideEffectOptions} [options] The option object.
  1408. * @returns {boolean} `true` if the node has a certain side effect.
  1409. */
  1410. function hasSideEffect(node, sourceCode, options = {}) {
  1411. const { considerGetters = false, considerImplicitTypeConversion = false } =
  1412. options;
  1413. return visitor.$visit(
  1414. node,
  1415. { considerGetters, considerImplicitTypeConversion },
  1416. sourceCode.visitorKeys || KEYS,
  1417. )
  1418. }
  1419. /** @typedef {import("estree").Node} Node */
  1420. /** @typedef {import("eslint").SourceCode} SourceCode */
  1421. /** @typedef {import("eslint").AST.Token} Token */
  1422. /** @typedef {import("eslint").Rule.Node} RuleNode */
  1423. /**
  1424. * Get the left parenthesis of the parent node syntax if it exists.
  1425. * E.g., `if (a) {}` then the `(`.
  1426. * @param {Node} node The AST node to check.
  1427. * @param {SourceCode} sourceCode The source code object to get tokens.
  1428. * @returns {Token|null} The left parenthesis of the parent node syntax
  1429. */
  1430. function getParentSyntaxParen(node, sourceCode) {
  1431. const parent = /** @type {RuleNode} */ (node).parent;
  1432. switch (parent.type) {
  1433. case "CallExpression":
  1434. case "NewExpression":
  1435. if (parent.arguments.length === 1 && parent.arguments[0] === node) {
  1436. return sourceCode.getTokenAfter(
  1437. parent.callee,
  1438. isOpeningParenToken,
  1439. )
  1440. }
  1441. return null
  1442. case "DoWhileStatement":
  1443. if (parent.test === node) {
  1444. return sourceCode.getTokenAfter(
  1445. parent.body,
  1446. isOpeningParenToken,
  1447. )
  1448. }
  1449. return null
  1450. case "IfStatement":
  1451. case "WhileStatement":
  1452. if (parent.test === node) {
  1453. return sourceCode.getFirstToken(parent, 1)
  1454. }
  1455. return null
  1456. case "ImportExpression":
  1457. if (parent.source === node) {
  1458. return sourceCode.getFirstToken(parent, 1)
  1459. }
  1460. return null
  1461. case "SwitchStatement":
  1462. if (parent.discriminant === node) {
  1463. return sourceCode.getFirstToken(parent, 1)
  1464. }
  1465. return null
  1466. case "WithStatement":
  1467. if (parent.object === node) {
  1468. return sourceCode.getFirstToken(parent, 1)
  1469. }
  1470. return null
  1471. default:
  1472. return null
  1473. }
  1474. }
  1475. /**
  1476. * Check whether a given node is parenthesized or not.
  1477. * @param {number} times The number of parantheses.
  1478. * @param {Node} node The AST node to check.
  1479. * @param {SourceCode} sourceCode The source code object to get tokens.
  1480. * @returns {boolean} `true` if the node is parenthesized the given times.
  1481. */
  1482. /**
  1483. * Check whether a given node is parenthesized or not.
  1484. * @param {Node} node The AST node to check.
  1485. * @param {SourceCode} sourceCode The source code object to get tokens.
  1486. * @returns {boolean} `true` if the node is parenthesized.
  1487. */
  1488. /**
  1489. * Check whether a given node is parenthesized or not.
  1490. * @param {Node|number} timesOrNode The first parameter.
  1491. * @param {Node|SourceCode} nodeOrSourceCode The second parameter.
  1492. * @param {SourceCode} [optionalSourceCode] The third parameter.
  1493. * @returns {boolean} `true` if the node is parenthesized.
  1494. */
  1495. function isParenthesized(
  1496. timesOrNode,
  1497. nodeOrSourceCode,
  1498. optionalSourceCode,
  1499. ) {
  1500. /** @type {number} */
  1501. let times,
  1502. /** @type {RuleNode} */
  1503. node,
  1504. /** @type {SourceCode} */
  1505. sourceCode,
  1506. maybeLeftParen,
  1507. maybeRightParen;
  1508. if (typeof timesOrNode === "number") {
  1509. times = timesOrNode | 0;
  1510. node = /** @type {RuleNode} */ (nodeOrSourceCode);
  1511. sourceCode = /** @type {SourceCode} */ (optionalSourceCode);
  1512. if (!(times >= 1)) {
  1513. throw new TypeError("'times' should be a positive integer.")
  1514. }
  1515. } else {
  1516. times = 1;
  1517. node = /** @type {RuleNode} */ (timesOrNode);
  1518. sourceCode = /** @type {SourceCode} */ (nodeOrSourceCode);
  1519. }
  1520. if (
  1521. node == null ||
  1522. // `Program` can't be parenthesized
  1523. node.parent == null ||
  1524. // `CatchClause.param` can't be parenthesized, example `try {} catch (error) {}`
  1525. (node.parent.type === "CatchClause" && node.parent.param === node)
  1526. ) {
  1527. return false
  1528. }
  1529. maybeLeftParen = maybeRightParen = node;
  1530. do {
  1531. maybeLeftParen = sourceCode.getTokenBefore(maybeLeftParen);
  1532. maybeRightParen = sourceCode.getTokenAfter(maybeRightParen);
  1533. } while (
  1534. maybeLeftParen != null &&
  1535. maybeRightParen != null &&
  1536. isOpeningParenToken(maybeLeftParen) &&
  1537. isClosingParenToken(maybeRightParen) &&
  1538. // Avoid false positive such as `if (a) {}`
  1539. maybeLeftParen !== getParentSyntaxParen(node, sourceCode) &&
  1540. --times > 0
  1541. )
  1542. return times === 0
  1543. }
  1544. /**
  1545. * @author Toru Nagashima <https://github.com/mysticatea>
  1546. * See LICENSE file in root directory for full license.
  1547. */
  1548. const placeholder = /\$(?:[$&`']|[1-9][0-9]?)/gu;
  1549. /** @type {WeakMap<PatternMatcher, {pattern:RegExp,escaped:boolean}>} */
  1550. const internal = new WeakMap();
  1551. /**
  1552. * Check whether a given character is escaped or not.
  1553. * @param {string} str The string to check.
  1554. * @param {number} index The location of the character to check.
  1555. * @returns {boolean} `true` if the character is escaped.
  1556. */
  1557. function isEscaped(str, index) {
  1558. let escaped = false;
  1559. for (let i = index - 1; i >= 0 && str.charCodeAt(i) === 0x5c; --i) {
  1560. escaped = !escaped;
  1561. }
  1562. return escaped
  1563. }
  1564. /**
  1565. * Replace a given string by a given matcher.
  1566. * @param {PatternMatcher} matcher The pattern matcher.
  1567. * @param {string} str The string to be replaced.
  1568. * @param {string} replacement The new substring to replace each matched part.
  1569. * @returns {string} The replaced string.
  1570. */
  1571. function replaceS(matcher, str, replacement) {
  1572. const chunks = [];
  1573. let index = 0;
  1574. /**
  1575. * @param {string} key The placeholder.
  1576. * @param {RegExpExecArray} match The matched information.
  1577. * @returns {string} The replaced string.
  1578. */
  1579. function replacer(key, match) {
  1580. switch (key) {
  1581. case "$$":
  1582. return "$"
  1583. case "$&":
  1584. return match[0]
  1585. case "$`":
  1586. return str.slice(0, match.index)
  1587. case "$'":
  1588. return str.slice(match.index + match[0].length)
  1589. default: {
  1590. const i = key.slice(1);
  1591. if (i in match) {
  1592. return match[/** @type {any} */ (i)]
  1593. }
  1594. return key
  1595. }
  1596. }
  1597. }
  1598. for (const match of matcher.execAll(str)) {
  1599. chunks.push(str.slice(index, match.index));
  1600. chunks.push(
  1601. replacement.replace(placeholder, (key) => replacer(key, match)),
  1602. );
  1603. index = match.index + match[0].length;
  1604. }
  1605. chunks.push(str.slice(index));
  1606. return chunks.join("")
  1607. }
  1608. /**
  1609. * Replace a given string by a given matcher.
  1610. * @param {PatternMatcher} matcher The pattern matcher.
  1611. * @param {string} str The string to be replaced.
  1612. * @param {(substring: string, ...args: any[]) => string} replace The function to replace each matched part.
  1613. * @returns {string} The replaced string.
  1614. */
  1615. function replaceF(matcher, str, replace) {
  1616. const chunks = [];
  1617. let index = 0;
  1618. for (const match of matcher.execAll(str)) {
  1619. chunks.push(str.slice(index, match.index));
  1620. chunks.push(
  1621. String(
  1622. replace(
  1623. .../** @type {[string, ...string[]]} */ (
  1624. /** @type {string[]} */ (match)
  1625. ),
  1626. match.index,
  1627. match.input,
  1628. ),
  1629. ),
  1630. );
  1631. index = match.index + match[0].length;
  1632. }
  1633. chunks.push(str.slice(index));
  1634. return chunks.join("")
  1635. }
  1636. /**
  1637. * The class to find patterns as considering escape sequences.
  1638. */
  1639. class PatternMatcher {
  1640. /**
  1641. * Initialize this matcher.
  1642. * @param {RegExp} pattern The pattern to match.
  1643. * @param {{escaped?:boolean}} [options] The options.
  1644. */
  1645. constructor(pattern, options = {}) {
  1646. const { escaped = false } = options;
  1647. if (!(pattern instanceof RegExp)) {
  1648. throw new TypeError("'pattern' should be a RegExp instance.")
  1649. }
  1650. if (!pattern.flags.includes("g")) {
  1651. throw new Error("'pattern' should contains 'g' flag.")
  1652. }
  1653. internal.set(this, {
  1654. pattern: new RegExp(pattern.source, pattern.flags),
  1655. escaped: Boolean(escaped),
  1656. });
  1657. }
  1658. /**
  1659. * Find the pattern in a given string.
  1660. * @param {string} str The string to find.
  1661. * @returns {IterableIterator<RegExpExecArray>} The iterator which iterate the matched information.
  1662. */
  1663. *execAll(str) {
  1664. const { pattern, escaped } =
  1665. /** @type {{pattern:RegExp,escaped:boolean}} */ (internal.get(this));
  1666. let match = null;
  1667. let lastIndex = 0;
  1668. pattern.lastIndex = 0;
  1669. while ((match = pattern.exec(str)) != null) {
  1670. if (escaped || !isEscaped(str, match.index)) {
  1671. lastIndex = pattern.lastIndex;
  1672. yield match;
  1673. pattern.lastIndex = lastIndex;
  1674. }
  1675. }
  1676. }
  1677. /**
  1678. * Check whether the pattern is found in a given string.
  1679. * @param {string} str The string to check.
  1680. * @returns {boolean} `true` if the pattern was found in the string.
  1681. */
  1682. test(str) {
  1683. const it = this.execAll(str);
  1684. const ret = it.next();
  1685. return !ret.done
  1686. }
  1687. /**
  1688. * Replace a given string.
  1689. * @param {string} str The string to be replaced.
  1690. * @param {(string|((...strs:string[])=>string))} replacer The string or function to replace. This is the same as the 2nd argument of `String.prototype.replace`.
  1691. * @returns {string} The replaced string.
  1692. */
  1693. [Symbol.replace](str, replacer) {
  1694. return typeof replacer === "function"
  1695. ? replaceF(this, String(str), replacer)
  1696. : replaceS(this, String(str), String(replacer))
  1697. }
  1698. }
  1699. /** @typedef {import("eslint").Scope.Scope} Scope */
  1700. /** @typedef {import("eslint").Scope.Variable} Variable */
  1701. /** @typedef {import("eslint").Rule.Node} RuleNode */
  1702. /** @typedef {import("estree").Node} Node */
  1703. /** @typedef {import("estree").Expression} Expression */
  1704. /** @typedef {import("estree").Pattern} Pattern */
  1705. /** @typedef {import("estree").Identifier} Identifier */
  1706. /** @typedef {import("estree").SimpleCallExpression} CallExpression */
  1707. /** @typedef {import("estree").Program} Program */
  1708. /** @typedef {import("estree").ImportDeclaration} ImportDeclaration */
  1709. /** @typedef {import("estree").ExportAllDeclaration} ExportAllDeclaration */
  1710. /** @typedef {import("estree").ExportDefaultDeclaration} ExportDefaultDeclaration */
  1711. /** @typedef {import("estree").ExportNamedDeclaration} ExportNamedDeclaration */
  1712. /** @typedef {import("estree").ImportSpecifier} ImportSpecifier */
  1713. /** @typedef {import("estree").ImportDefaultSpecifier} ImportDefaultSpecifier */
  1714. /** @typedef {import("estree").ImportNamespaceSpecifier} ImportNamespaceSpecifier */
  1715. /** @typedef {import("estree").ExportSpecifier} ExportSpecifier */
  1716. /** @typedef {import("estree").Property} Property */
  1717. /** @typedef {import("estree").AssignmentProperty} AssignmentProperty */
  1718. /** @typedef {import("estree").Literal} Literal */
  1719. /** @typedef {import("@typescript-eslint/types").TSESTree.Node} TSESTreeNode */
  1720. /** @typedef {import("./types.mjs").ReferenceTrackerOptions} ReferenceTrackerOptions */
  1721. /**
  1722. * @template T
  1723. * @typedef {import("./types.mjs").TraceMap<T>} TraceMap
  1724. */
  1725. /**
  1726. * @template T
  1727. * @typedef {import("./types.mjs").TraceMapObject<T>} TraceMapObject
  1728. */
  1729. /**
  1730. * @template T
  1731. * @typedef {import("./types.mjs").TrackedReferences<T>} TrackedReferences
  1732. */
  1733. const IMPORT_TYPE = /^(?:Import|Export(?:All|Default|Named))Declaration$/u;
  1734. /**
  1735. * Check whether a given node is an import node or not.
  1736. * @param {Node} node
  1737. * @returns {node is ImportDeclaration|ExportAllDeclaration|ExportNamedDeclaration&{source: Literal}} `true` if the node is an import node.
  1738. */
  1739. function isHasSource(node) {
  1740. return (
  1741. IMPORT_TYPE.test(node.type) &&
  1742. /** @type {ImportDeclaration|ExportAllDeclaration|ExportNamedDeclaration} */ (
  1743. node
  1744. ).source != null
  1745. )
  1746. }
  1747. const has =
  1748. /** @type {<T>(traceMap: TraceMap<unknown>, v: T) => v is (string extends T ? string : T)} */ (
  1749. Function.call.bind(Object.hasOwnProperty)
  1750. );
  1751. const READ = Symbol("read");
  1752. const CALL = Symbol("call");
  1753. const CONSTRUCT = Symbol("construct");
  1754. const ESM = Symbol("esm");
  1755. const requireCall = { require: { [CALL]: true } };
  1756. /**
  1757. * Check whether a given variable is modified or not.
  1758. * @param {Variable|undefined} variable The variable to check.
  1759. * @returns {boolean} `true` if the variable is modified.
  1760. */
  1761. function isModifiedGlobal(variable) {
  1762. return (
  1763. variable == null ||
  1764. variable.defs.length !== 0 ||
  1765. variable.references.some((r) => r.isWrite())
  1766. )
  1767. }
  1768. /**
  1769. * Check if the value of a given node is passed through to the parent syntax as-is.
  1770. * For example, `a` and `b` in (`a || b` and `c ? a : b`) are passed through.
  1771. * @param {Node} node A node to check.
  1772. * @returns {node is RuleNode & {parent: Expression}} `true` if the node is passed through.
  1773. */
  1774. function isPassThrough(node) {
  1775. const parent = /** @type {TSESTreeNode} */ (node).parent;
  1776. if (parent) {
  1777. switch (parent.type) {
  1778. case "ConditionalExpression":
  1779. return parent.consequent === node || parent.alternate === node
  1780. case "LogicalExpression":
  1781. return true
  1782. case "SequenceExpression":
  1783. return (
  1784. parent.expressions[parent.expressions.length - 1] === node
  1785. )
  1786. case "ChainExpression":
  1787. return true
  1788. case "TSAsExpression":
  1789. case "TSSatisfiesExpression":
  1790. case "TSTypeAssertion":
  1791. case "TSNonNullExpression":
  1792. case "TSInstantiationExpression":
  1793. return true
  1794. default:
  1795. return false
  1796. }
  1797. }
  1798. return false
  1799. }
  1800. /**
  1801. * The reference tracker.
  1802. */
  1803. class ReferenceTracker {
  1804. /**
  1805. * Initialize this tracker.
  1806. * @param {Scope} globalScope The global scope.
  1807. * @param {object} [options] The options.
  1808. * @param {"legacy"|"strict"} [options.mode="strict"] The mode to determine the ImportDeclaration's behavior for CJS modules.
  1809. * @param {string[]} [options.globalObjectNames=["global","globalThis","self","window"]] The variable names for Global Object.
  1810. */
  1811. constructor(globalScope, options = {}) {
  1812. const {
  1813. mode = "strict",
  1814. globalObjectNames = ["global", "globalThis", "self", "window"],
  1815. } = options;
  1816. /** @private @type {Variable[]} */
  1817. this.variableStack = [];
  1818. /** @private */
  1819. this.globalScope = globalScope;
  1820. /** @private */
  1821. this.mode = mode;
  1822. /** @private */
  1823. this.globalObjectNames = globalObjectNames.slice(0);
  1824. }
  1825. /**
  1826. * Iterate the references of global variables.
  1827. * @template T
  1828. * @param {TraceMap<T>} traceMap The trace map.
  1829. * @returns {IterableIterator<TrackedReferences<T>>} The iterator to iterate references.
  1830. */
  1831. *iterateGlobalReferences(traceMap) {
  1832. for (const key of Object.keys(traceMap)) {
  1833. const nextTraceMap = traceMap[key];
  1834. const path = [key];
  1835. const variable = this.globalScope.set.get(key);
  1836. if (isModifiedGlobal(variable)) {
  1837. continue
  1838. }
  1839. yield* this._iterateVariableReferences(
  1840. /** @type {Variable} */ (variable),
  1841. path,
  1842. nextTraceMap,
  1843. true,
  1844. );
  1845. }
  1846. for (const key of this.globalObjectNames) {
  1847. /** @type {string[]} */
  1848. const path = [];
  1849. const variable = this.globalScope.set.get(key);
  1850. if (isModifiedGlobal(variable)) {
  1851. continue
  1852. }
  1853. yield* this._iterateVariableReferences(
  1854. /** @type {Variable} */ (variable),
  1855. path,
  1856. traceMap,
  1857. false,
  1858. );
  1859. }
  1860. }
  1861. /**
  1862. * Iterate the references of CommonJS modules.
  1863. * @template T
  1864. * @param {TraceMap<T>} traceMap The trace map.
  1865. * @returns {IterableIterator<TrackedReferences<T>>} The iterator to iterate references.
  1866. */
  1867. *iterateCjsReferences(traceMap) {
  1868. for (const { node } of this.iterateGlobalReferences(requireCall)) {
  1869. const key = getStringIfConstant(
  1870. /** @type {CallExpression} */ (node).arguments[0],
  1871. );
  1872. if (key == null || !has(traceMap, key)) {
  1873. continue
  1874. }
  1875. const nextTraceMap = traceMap[key];
  1876. const path = [key];
  1877. if (nextTraceMap[READ]) {
  1878. yield {
  1879. node,
  1880. path,
  1881. type: READ,
  1882. info: nextTraceMap[READ],
  1883. };
  1884. }
  1885. yield* this._iteratePropertyReferences(
  1886. /** @type {CallExpression} */ (node),
  1887. path,
  1888. nextTraceMap,
  1889. );
  1890. }
  1891. }
  1892. /**
  1893. * Iterate the references of ES modules.
  1894. * @template T
  1895. * @param {TraceMap<T>} traceMap The trace map.
  1896. * @returns {IterableIterator<TrackedReferences<T>>} The iterator to iterate references.
  1897. */
  1898. *iterateEsmReferences(traceMap) {
  1899. const programNode = /** @type {Program} */ (this.globalScope.block);
  1900. for (const node of programNode.body) {
  1901. if (!isHasSource(node)) {
  1902. continue
  1903. }
  1904. const moduleId = /** @type {string} */ (node.source.value);
  1905. if (!has(traceMap, moduleId)) {
  1906. continue
  1907. }
  1908. const nextTraceMap = traceMap[moduleId];
  1909. const path = [moduleId];
  1910. if (nextTraceMap[READ]) {
  1911. yield {
  1912. // eslint-disable-next-line object-shorthand -- apply type
  1913. node: /** @type {RuleNode} */ (node),
  1914. path,
  1915. type: READ,
  1916. info: nextTraceMap[READ],
  1917. };
  1918. }
  1919. if (node.type === "ExportAllDeclaration") {
  1920. for (const key of Object.keys(nextTraceMap)) {
  1921. const exportTraceMap = nextTraceMap[key];
  1922. if (exportTraceMap[READ]) {
  1923. yield {
  1924. // eslint-disable-next-line object-shorthand -- apply type
  1925. node: /** @type {RuleNode} */ (node),
  1926. path: path.concat(key),
  1927. type: READ,
  1928. info: exportTraceMap[READ],
  1929. };
  1930. }
  1931. }
  1932. } else {
  1933. for (const specifier of node.specifiers) {
  1934. const esm = has(nextTraceMap, ESM);
  1935. const it = this._iterateImportReferences(
  1936. specifier,
  1937. path,
  1938. esm
  1939. ? nextTraceMap
  1940. : this.mode === "legacy"
  1941. ? { default: nextTraceMap, ...nextTraceMap }
  1942. : { default: nextTraceMap },
  1943. );
  1944. if (esm) {
  1945. yield* it;
  1946. } else {
  1947. for (const report of it) {
  1948. report.path = report.path.filter(exceptDefault);
  1949. if (
  1950. report.path.length >= 2 ||
  1951. report.type !== READ
  1952. ) {
  1953. yield report;
  1954. }
  1955. }
  1956. }
  1957. }
  1958. }
  1959. }
  1960. }
  1961. /**
  1962. * Iterate the property references for a given expression AST node.
  1963. * @template T
  1964. * @param {Expression} node The expression AST node to iterate property references.
  1965. * @param {TraceMap<T>} traceMap The trace map.
  1966. * @returns {IterableIterator<TrackedReferences<T>>} The iterator to iterate property references.
  1967. */
  1968. *iteratePropertyReferences(node, traceMap) {
  1969. yield* this._iteratePropertyReferences(node, [], traceMap);
  1970. }
  1971. /**
  1972. * Iterate the references for a given variable.
  1973. * @private
  1974. * @template T
  1975. * @param {Variable} variable The variable to iterate that references.
  1976. * @param {string[]} path The current path.
  1977. * @param {TraceMapObject<T>} traceMap The trace map.
  1978. * @param {boolean} shouldReport = The flag to report those references.
  1979. * @returns {IterableIterator<TrackedReferences<T>>} The iterator to iterate references.
  1980. */
  1981. *_iterateVariableReferences(variable, path, traceMap, shouldReport) {
  1982. if (this.variableStack.includes(variable)) {
  1983. return
  1984. }
  1985. this.variableStack.push(variable);
  1986. try {
  1987. for (const reference of variable.references) {
  1988. if (!reference.isRead()) {
  1989. continue
  1990. }
  1991. const node = /** @type {RuleNode & Identifier} */ (
  1992. reference.identifier
  1993. );
  1994. if (shouldReport && traceMap[READ]) {
  1995. yield { node, path, type: READ, info: traceMap[READ] };
  1996. }
  1997. yield* this._iteratePropertyReferences(node, path, traceMap);
  1998. }
  1999. } finally {
  2000. this.variableStack.pop();
  2001. }
  2002. }
  2003. /**
  2004. * Iterate the references for a given AST node.
  2005. * @private
  2006. * @template T
  2007. * @param {Expression} rootNode The AST node to iterate references.
  2008. * @param {string[]} path The current path.
  2009. * @param {TraceMapObject<T>} traceMap The trace map.
  2010. * @returns {IterableIterator<TrackedReferences<T>>} The iterator to iterate references.
  2011. */
  2012. //eslint-disable-next-line complexity
  2013. *_iteratePropertyReferences(rootNode, path, traceMap) {
  2014. let node = rootNode;
  2015. while (isPassThrough(node)) {
  2016. node = node.parent;
  2017. }
  2018. const parent = /** @type {RuleNode} */ (node).parent;
  2019. if (parent.type === "MemberExpression") {
  2020. if (parent.object === node) {
  2021. const key = getPropertyName(parent);
  2022. if (key == null || !has(traceMap, key)) {
  2023. return
  2024. }
  2025. path = path.concat(key); //eslint-disable-line no-param-reassign
  2026. const nextTraceMap = traceMap[key];
  2027. if (nextTraceMap[READ]) {
  2028. yield {
  2029. node: parent,
  2030. path,
  2031. type: READ,
  2032. info: nextTraceMap[READ],
  2033. };
  2034. }
  2035. yield* this._iteratePropertyReferences(
  2036. parent,
  2037. path,
  2038. nextTraceMap,
  2039. );
  2040. }
  2041. return
  2042. }
  2043. if (parent.type === "CallExpression") {
  2044. if (parent.callee === node && traceMap[CALL]) {
  2045. yield { node: parent, path, type: CALL, info: traceMap[CALL] };
  2046. }
  2047. return
  2048. }
  2049. if (parent.type === "NewExpression") {
  2050. if (parent.callee === node && traceMap[CONSTRUCT]) {
  2051. yield {
  2052. node: parent,
  2053. path,
  2054. type: CONSTRUCT,
  2055. info: traceMap[CONSTRUCT],
  2056. };
  2057. }
  2058. return
  2059. }
  2060. if (parent.type === "AssignmentExpression") {
  2061. if (parent.right === node) {
  2062. yield* this._iterateLhsReferences(parent.left, path, traceMap);
  2063. yield* this._iteratePropertyReferences(parent, path, traceMap);
  2064. }
  2065. return
  2066. }
  2067. if (parent.type === "AssignmentPattern") {
  2068. if (parent.right === node) {
  2069. yield* this._iterateLhsReferences(parent.left, path, traceMap);
  2070. }
  2071. return
  2072. }
  2073. if (parent.type === "VariableDeclarator") {
  2074. if (parent.init === node) {
  2075. yield* this._iterateLhsReferences(parent.id, path, traceMap);
  2076. }
  2077. }
  2078. }
  2079. /**
  2080. * Iterate the references for a given Pattern node.
  2081. * @private
  2082. * @template T
  2083. * @param {Pattern} patternNode The Pattern node to iterate references.
  2084. * @param {string[]} path The current path.
  2085. * @param {TraceMapObject<T>} traceMap The trace map.
  2086. * @returns {IterableIterator<TrackedReferences<T>>} The iterator to iterate references.
  2087. */
  2088. *_iterateLhsReferences(patternNode, path, traceMap) {
  2089. if (patternNode.type === "Identifier") {
  2090. const variable = findVariable(this.globalScope, patternNode);
  2091. if (variable != null) {
  2092. yield* this._iterateVariableReferences(
  2093. variable,
  2094. path,
  2095. traceMap,
  2096. false,
  2097. );
  2098. }
  2099. return
  2100. }
  2101. if (patternNode.type === "ObjectPattern") {
  2102. for (const property of patternNode.properties) {
  2103. const key = getPropertyName(
  2104. /** @type {AssignmentProperty} */ (property),
  2105. );
  2106. if (key == null || !has(traceMap, key)) {
  2107. continue
  2108. }
  2109. const nextPath = path.concat(key);
  2110. const nextTraceMap = traceMap[key];
  2111. if (nextTraceMap[READ]) {
  2112. yield {
  2113. node: /** @type {RuleNode} */ (property),
  2114. path: nextPath,
  2115. type: READ,
  2116. info: nextTraceMap[READ],
  2117. };
  2118. }
  2119. yield* this._iterateLhsReferences(
  2120. /** @type {AssignmentProperty} */ (property).value,
  2121. nextPath,
  2122. nextTraceMap,
  2123. );
  2124. }
  2125. return
  2126. }
  2127. if (patternNode.type === "AssignmentPattern") {
  2128. yield* this._iterateLhsReferences(patternNode.left, path, traceMap);
  2129. }
  2130. }
  2131. /**
  2132. * Iterate the references for a given ModuleSpecifier node.
  2133. * @private
  2134. * @template T
  2135. * @param {ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ExportSpecifier} specifierNode The ModuleSpecifier node to iterate references.
  2136. * @param {string[]} path The current path.
  2137. * @param {TraceMapObject<T>} traceMap The trace map.
  2138. * @returns {IterableIterator<TrackedReferences<T>>} The iterator to iterate references.
  2139. */
  2140. *_iterateImportReferences(specifierNode, path, traceMap) {
  2141. const type = specifierNode.type;
  2142. if (type === "ImportSpecifier" || type === "ImportDefaultSpecifier") {
  2143. const key =
  2144. type === "ImportDefaultSpecifier"
  2145. ? "default"
  2146. : specifierNode.imported.type === "Identifier"
  2147. ? specifierNode.imported.name
  2148. : specifierNode.imported.value;
  2149. if (!has(traceMap, key)) {
  2150. return
  2151. }
  2152. path = path.concat(key); //eslint-disable-line no-param-reassign
  2153. const nextTraceMap = traceMap[key];
  2154. if (nextTraceMap[READ]) {
  2155. yield {
  2156. node: /** @type {RuleNode} */ (specifierNode),
  2157. path,
  2158. type: READ,
  2159. info: nextTraceMap[READ],
  2160. };
  2161. }
  2162. yield* this._iterateVariableReferences(
  2163. /** @type {Variable} */ (
  2164. findVariable(this.globalScope, specifierNode.local)
  2165. ),
  2166. path,
  2167. nextTraceMap,
  2168. false,
  2169. );
  2170. return
  2171. }
  2172. if (type === "ImportNamespaceSpecifier") {
  2173. yield* this._iterateVariableReferences(
  2174. /** @type {Variable} */ (
  2175. findVariable(this.globalScope, specifierNode.local)
  2176. ),
  2177. path,
  2178. traceMap,
  2179. false,
  2180. );
  2181. return
  2182. }
  2183. if (type === "ExportSpecifier") {
  2184. const key =
  2185. specifierNode.local.type === "Identifier"
  2186. ? specifierNode.local.name
  2187. : specifierNode.local.value;
  2188. if (!has(traceMap, key)) {
  2189. return
  2190. }
  2191. path = path.concat(key); //eslint-disable-line no-param-reassign
  2192. const nextTraceMap = traceMap[key];
  2193. if (nextTraceMap[READ]) {
  2194. yield {
  2195. node: /** @type {RuleNode} */ (specifierNode),
  2196. path,
  2197. type: READ,
  2198. info: nextTraceMap[READ],
  2199. };
  2200. }
  2201. }
  2202. }
  2203. }
  2204. ReferenceTracker.READ = READ;
  2205. ReferenceTracker.CALL = CALL;
  2206. ReferenceTracker.CONSTRUCT = CONSTRUCT;
  2207. ReferenceTracker.ESM = ESM;
  2208. /**
  2209. * This is a predicate function for Array#filter.
  2210. * @param {string} name A name part.
  2211. * @param {number} index The index of the name.
  2212. * @returns {boolean} `false` if it's default.
  2213. */
  2214. function exceptDefault(name, index) {
  2215. return !(index === 1 && name === "default")
  2216. }
  2217. /** @typedef {import("./types.mjs").StaticValue} StaticValue */
  2218. var index = {
  2219. CALL,
  2220. CONSTRUCT,
  2221. ESM,
  2222. findVariable,
  2223. getFunctionHeadLocation,
  2224. getFunctionNameWithKind,
  2225. getInnermostScope,
  2226. getPropertyName,
  2227. getStaticValue,
  2228. getStringIfConstant,
  2229. hasSideEffect,
  2230. isArrowToken,
  2231. isClosingBraceToken,
  2232. isClosingBracketToken,
  2233. isClosingParenToken,
  2234. isColonToken,
  2235. isCommaToken,
  2236. isCommentToken,
  2237. isNotArrowToken,
  2238. isNotClosingBraceToken,
  2239. isNotClosingBracketToken,
  2240. isNotClosingParenToken,
  2241. isNotColonToken,
  2242. isNotCommaToken,
  2243. isNotCommentToken,
  2244. isNotOpeningBraceToken,
  2245. isNotOpeningBracketToken,
  2246. isNotOpeningParenToken,
  2247. isNotSemicolonToken,
  2248. isOpeningBraceToken,
  2249. isOpeningBracketToken,
  2250. isOpeningParenToken,
  2251. isParenthesized,
  2252. isSemicolonToken,
  2253. PatternMatcher,
  2254. READ,
  2255. ReferenceTracker,
  2256. };
  2257. export { CALL, CONSTRUCT, ESM, PatternMatcher, READ, ReferenceTracker, index as default, findVariable, getFunctionHeadLocation, getFunctionNameWithKind, getInnermostScope, getPropertyName, getStaticValue, getStringIfConstant, hasSideEffect, isArrowToken, isClosingBraceToken, isClosingBracketToken, isClosingParenToken, isColonToken, isCommaToken, isCommentToken, isNotArrowToken, isNotClosingBraceToken, isNotClosingBracketToken, isNotClosingParenToken, isNotColonToken, isNotCommaToken, isNotCommentToken, isNotOpeningBraceToken, isNotOpeningBracketToken, isNotOpeningParenToken, isNotSemicolonToken, isOpeningBraceToken, isOpeningBracketToken, isOpeningParenToken, isParenthesized, isSemicolonToken };
  2258. //# sourceMappingURL=index.mjs.map