index.mjs 85 KB

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