index.js 82 KB

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