eslint 8.57.1 → 9.39.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (458) hide show
  1. package/README.md +165 -115
  2. package/bin/eslint.js +112 -89
  3. package/conf/default-cli-options.js +22 -22
  4. package/conf/ecma-version.js +16 -0
  5. package/conf/globals.js +109 -94
  6. package/conf/replacements.json +24 -20
  7. package/conf/rule-type-list.json +89 -26
  8. package/lib/api.js +16 -20
  9. package/lib/cli-engine/cli-engine.js +841 -810
  10. package/lib/cli-engine/file-enumerator.js +384 -390
  11. package/lib/cli-engine/formatters/formatters-meta.json +17 -45
  12. package/lib/cli-engine/formatters/html.js +110 -102
  13. package/lib/cli-engine/formatters/json-with-metadata.js +5 -5
  14. package/lib/cli-engine/formatters/json.js +2 -2
  15. package/lib/cli-engine/formatters/stylish.js +97 -76
  16. package/lib/cli-engine/hash.js +1 -1
  17. package/lib/cli-engine/index.js +1 -1
  18. package/lib/cli-engine/lint-result-cache.js +165 -148
  19. package/lib/cli-engine/load-rules.js +17 -17
  20. package/lib/cli.js +481 -399
  21. package/lib/config/config-loader.js +816 -0
  22. package/lib/config/config.js +674 -0
  23. package/lib/config/default-config.js +57 -46
  24. package/lib/config/flat-config-array.js +170 -333
  25. package/lib/config/flat-config-schema.js +389 -389
  26. package/lib/config-api.js +12 -0
  27. package/lib/eslint/eslint-helpers.js +1196 -663
  28. package/lib/eslint/eslint.js +1262 -607
  29. package/lib/eslint/index.js +3 -3
  30. package/lib/eslint/legacy-eslint.js +786 -0
  31. package/lib/eslint/worker.js +173 -0
  32. package/lib/languages/js/index.js +336 -0
  33. package/lib/languages/js/source-code/index.js +7 -0
  34. package/lib/languages/js/source-code/source-code.js +1364 -0
  35. package/lib/languages/js/source-code/token-store/backward-token-comment-cursor.js +61 -0
  36. package/lib/languages/js/source-code/token-store/backward-token-cursor.js +57 -0
  37. package/lib/{source-code → languages/js/source-code}/token-store/cursor.js +36 -36
  38. package/lib/languages/js/source-code/token-store/cursors.js +120 -0
  39. package/lib/{source-code → languages/js/source-code}/token-store/decorative-cursor.js +17 -18
  40. package/lib/{source-code → languages/js/source-code}/token-store/filter-cursor.js +19 -20
  41. package/lib/languages/js/source-code/token-store/forward-token-comment-cursor.js +65 -0
  42. package/lib/languages/js/source-code/token-store/forward-token-cursor.js +62 -0
  43. package/lib/languages/js/source-code/token-store/index.js +721 -0
  44. package/lib/{source-code → languages/js/source-code}/token-store/limit-cursor.js +17 -18
  45. package/lib/languages/js/source-code/token-store/padded-token-cursor.js +45 -0
  46. package/lib/{source-code → languages/js/source-code}/token-store/skip-cursor.js +19 -20
  47. package/lib/languages/js/source-code/token-store/utils.js +110 -0
  48. package/lib/languages/js/validate-language-options.js +196 -0
  49. package/lib/linter/apply-disable-directives.js +490 -371
  50. package/lib/linter/code-path-analysis/code-path-analyzer.js +650 -674
  51. package/lib/linter/code-path-analysis/code-path-segment.js +215 -216
  52. package/lib/linter/code-path-analysis/code-path-state.js +2118 -2096
  53. package/lib/linter/code-path-analysis/code-path.js +307 -317
  54. package/lib/linter/code-path-analysis/debug-helpers.js +183 -163
  55. package/lib/linter/code-path-analysis/fork-context.js +297 -272
  56. package/lib/linter/code-path-analysis/id-generator.js +22 -23
  57. package/lib/linter/esquery.js +332 -0
  58. package/lib/linter/file-context.js +144 -0
  59. package/lib/linter/file-report.js +608 -0
  60. package/lib/linter/index.js +3 -5
  61. package/lib/linter/interpolate.js +38 -16
  62. package/lib/linter/linter.js +2328 -1785
  63. package/lib/linter/rule-fixer.js +136 -107
  64. package/lib/linter/rules.js +37 -46
  65. package/lib/linter/source-code-fixer.js +96 -94
  66. package/lib/linter/source-code-traverser.js +333 -0
  67. package/lib/linter/source-code-visitor.js +81 -0
  68. package/lib/linter/timing.js +145 -97
  69. package/lib/linter/vfile.js +115 -0
  70. package/lib/options.js +464 -326
  71. package/lib/rule-tester/index.js +3 -1
  72. package/lib/rule-tester/rule-tester.js +1371 -998
  73. package/lib/rules/accessor-pairs.js +333 -259
  74. package/lib/rules/array-bracket-newline.js +250 -220
  75. package/lib/rules/array-bracket-spacing.js +286 -229
  76. package/lib/rules/array-callback-return.js +401 -354
  77. package/lib/rules/array-element-newline.js +358 -295
  78. package/lib/rules/arrow-body-style.js +400 -278
  79. package/lib/rules/arrow-parens.js +206 -155
  80. package/lib/rules/arrow-spacing.js +169 -145
  81. package/lib/rules/block-scoped-var.js +125 -123
  82. package/lib/rules/block-spacing.js +186 -158
  83. package/lib/rules/brace-style.js +262 -181
  84. package/lib/rules/callback-return.js +203 -174
  85. package/lib/rules/camelcase.js +403 -380
  86. package/lib/rules/capitalized-comments.js +253 -228
  87. package/lib/rules/class-methods-use-this.js +231 -168
  88. package/lib/rules/comma-dangle.js +379 -328
  89. package/lib/rules/comma-spacing.js +193 -177
  90. package/lib/rules/comma-style.js +375 -298
  91. package/lib/rules/complexity.js +180 -144
  92. package/lib/rules/computed-property-spacing.js +236 -193
  93. package/lib/rules/consistent-return.js +181 -170
  94. package/lib/rules/consistent-this.js +167 -141
  95. package/lib/rules/constructor-super.js +418 -411
  96. package/lib/rules/curly.js +407 -468
  97. package/lib/rules/default-case-last.js +39 -32
  98. package/lib/rules/default-case.js +89 -83
  99. package/lib/rules/default-param-last.js +69 -53
  100. package/lib/rules/dot-location.js +122 -92
  101. package/lib/rules/dot-notation.js +193 -153
  102. package/lib/rules/eol-last.js +122 -102
  103. package/lib/rules/eqeqeq.js +191 -155
  104. package/lib/rules/for-direction.js +150 -122
  105. package/lib/rules/func-call-spacing.js +261 -213
  106. package/lib/rules/func-name-matching.js +294 -209
  107. package/lib/rules/func-names.js +165 -164
  108. package/lib/rules/func-style.js +209 -86
  109. package/lib/rules/function-call-argument-newline.js +152 -111
  110. package/lib/rules/function-paren-newline.js +349 -273
  111. package/lib/rules/generator-star-spacing.js +229 -192
  112. package/lib/rules/getter-return.js +208 -170
  113. package/lib/rules/global-require.js +85 -58
  114. package/lib/rules/grouped-accessor-pairs.js +201 -148
  115. package/lib/rules/guard-for-in.js +72 -63
  116. package/lib/rules/handle-callback-err.js +108 -87
  117. package/lib/rules/id-blacklist.js +182 -187
  118. package/lib/rules/id-denylist.js +174 -179
  119. package/lib/rules/id-length.js +197 -157
  120. package/lib/rules/id-match.js +350 -286
  121. package/lib/rules/implicit-arrow-linebreak.js +102 -61
  122. package/lib/rules/indent-legacy.js +1345 -1102
  123. package/lib/rules/indent.js +2272 -1741
  124. package/lib/rules/index.js +320 -294
  125. package/lib/rules/init-declarations.js +139 -106
  126. package/lib/rules/jsx-quotes.js +94 -64
  127. package/lib/rules/key-spacing.js +750 -615
  128. package/lib/rules/keyword-spacing.js +648 -587
  129. package/lib/rules/line-comment-position.js +143 -108
  130. package/lib/rules/linebreak-style.js +115 -88
  131. package/lib/rules/lines-around-comment.js +540 -430
  132. package/lib/rules/lines-around-directive.js +233 -185
  133. package/lib/rules/lines-between-class-members.js +305 -216
  134. package/lib/rules/logical-assignment-operators.js +582 -398
  135. package/lib/rules/max-classes-per-file.js +69 -68
  136. package/lib/rules/max-depth.js +146 -143
  137. package/lib/rules/max-len.js +473 -416
  138. package/lib/rules/max-lines-per-function.js +201 -176
  139. package/lib/rules/max-lines.js +158 -162
  140. package/lib/rules/max-nested-callbacks.js +102 -104
  141. package/lib/rules/max-params.js +102 -75
  142. package/lib/rules/max-statements-per-line.js +205 -180
  143. package/lib/rules/max-statements.js +168 -164
  144. package/lib/rules/multiline-comment-style.js +638 -460
  145. package/lib/rules/multiline-ternary.js +241 -158
  146. package/lib/rules/new-cap.js +233 -232
  147. package/lib/rules/new-parens.js +88 -61
  148. package/lib/rules/newline-after-var.js +287 -233
  149. package/lib/rules/newline-before-return.js +229 -204
  150. package/lib/rules/newline-per-chained-call.js +142 -109
  151. package/lib/rules/no-alert.js +90 -79
  152. package/lib/rules/no-array-constructor.js +175 -113
  153. package/lib/rules/no-async-promise-executor.js +30 -24
  154. package/lib/rules/no-await-in-loop.js +79 -70
  155. package/lib/rules/no-bitwise.js +113 -87
  156. package/lib/rules/no-buffer-constructor.js +61 -37
  157. package/lib/rules/no-caller.js +39 -33
  158. package/lib/rules/no-case-declarations.js +61 -45
  159. package/lib/rules/no-catch-shadow.js +76 -62
  160. package/lib/rules/no-class-assign.js +51 -48
  161. package/lib/rules/no-compare-neg-zero.js +62 -48
  162. package/lib/rules/no-cond-assign.js +148 -132
  163. package/lib/rules/no-confusing-arrow.js +98 -63
  164. package/lib/rules/no-console.js +202 -188
  165. package/lib/rules/no-const-assign.js +58 -41
  166. package/lib/rules/no-constant-binary-expression.js +501 -407
  167. package/lib/rules/no-constant-condition.js +158 -131
  168. package/lib/rules/no-constructor-return.js +49 -49
  169. package/lib/rules/no-continue.js +25 -26
  170. package/lib/rules/no-control-regex.js +125 -121
  171. package/lib/rules/no-debugger.js +28 -30
  172. package/lib/rules/no-delete-var.js +29 -29
  173. package/lib/rules/no-div-regex.js +47 -40
  174. package/lib/rules/no-dupe-args.js +79 -69
  175. package/lib/rules/no-dupe-class-members.js +102 -89
  176. package/lib/rules/no-dupe-else-if.js +100 -77
  177. package/lib/rules/no-dupe-keys.js +133 -110
  178. package/lib/rules/no-duplicate-case.js +50 -43
  179. package/lib/rules/no-duplicate-imports.js +266 -188
  180. package/lib/rules/no-else-return.js +430 -385
  181. package/lib/rules/no-empty-character-class.js +57 -50
  182. package/lib/rules/no-empty-function.js +197 -128
  183. package/lib/rules/no-empty-pattern.js +63 -56
  184. package/lib/rules/no-empty-static-block.js +61 -35
  185. package/lib/rules/no-empty.js +135 -85
  186. package/lib/rules/no-eq-null.js +37 -32
  187. package/lib/rules/no-eval.js +258 -249
  188. package/lib/rules/no-ex-assign.js +42 -39
  189. package/lib/rules/no-extend-native.js +161 -160
  190. package/lib/rules/no-extra-bind.js +201 -190
  191. package/lib/rules/no-extra-boolean-cast.js +398 -295
  192. package/lib/rules/no-extra-label.js +150 -130
  193. package/lib/rules/no-extra-parens.js +1654 -1307
  194. package/lib/rules/no-extra-semi.js +146 -126
  195. package/lib/rules/no-fallthrough.js +200 -136
  196. package/lib/rules/no-floating-decimal.js +74 -48
  197. package/lib/rules/no-func-assign.js +54 -55
  198. package/lib/rules/no-global-assign.js +78 -72
  199. package/lib/rules/no-implicit-coercion.js +350 -262
  200. package/lib/rules/no-implicit-globals.js +174 -133
  201. package/lib/rules/no-implied-eval.js +150 -112
  202. package/lib/rules/no-import-assign.js +145 -159
  203. package/lib/rules/no-inline-comments.js +101 -96
  204. package/lib/rules/no-inner-declarations.js +115 -78
  205. package/lib/rules/no-invalid-regexp.js +223 -174
  206. package/lib/rules/no-invalid-this.js +145 -117
  207. package/lib/rules/no-irregular-whitespace.js +266 -250
  208. package/lib/rules/no-iterator.js +29 -33
  209. package/lib/rules/no-label-var.js +59 -61
  210. package/lib/rules/no-labels.js +138 -131
  211. package/lib/rules/no-lone-blocks.js +127 -123
  212. package/lib/rules/no-lonely-if.js +105 -67
  213. package/lib/rules/no-loop-func.js +245 -184
  214. package/lib/rules/no-loss-of-precision.js +236 -201
  215. package/lib/rules/no-magic-numbers.js +339 -217
  216. package/lib/rules/no-misleading-character-class.js +548 -253
  217. package/lib/rules/no-mixed-operators.js +188 -164
  218. package/lib/rules/no-mixed-requires.js +253 -224
  219. package/lib/rules/no-mixed-spaces-and-tabs.js +135 -103
  220. package/lib/rules/no-multi-assign.js +46 -47
  221. package/lib/rules/no-multi-spaces.js +163 -125
  222. package/lib/rules/no-multi-str.js +42 -40
  223. package/lib/rules/no-multiple-empty-lines.js +196 -140
  224. package/lib/rules/no-native-reassign.js +90 -74
  225. package/lib/rules/no-negated-condition.js +79 -74
  226. package/lib/rules/no-negated-in-lhs.js +45 -32
  227. package/lib/rules/no-nested-ternary.js +33 -31
  228. package/lib/rules/no-new-func.js +71 -62
  229. package/lib/rules/no-new-native-nonconstructor.js +43 -39
  230. package/lib/rules/no-new-object.js +48 -39
  231. package/lib/rules/no-new-require.js +48 -31
  232. package/lib/rules/no-new-symbol.js +61 -43
  233. package/lib/rules/no-new-wrappers.js +43 -41
  234. package/lib/rules/no-new.js +28 -29
  235. package/lib/rules/no-nonoctal-decimal-escape.js +149 -121
  236. package/lib/rules/no-obj-calls.js +66 -53
  237. package/lib/rules/no-object-constructor.js +104 -97
  238. package/lib/rules/no-octal-escape.js +40 -43
  239. package/lib/rules/no-octal.js +29 -32
  240. package/lib/rules/no-param-reassign.js +236 -218
  241. package/lib/rules/no-path-concat.js +66 -51
  242. package/lib/rules/no-plusplus.js +60 -63
  243. package/lib/rules/no-process-env.js +49 -32
  244. package/lib/rules/no-process-exit.js +48 -28
  245. package/lib/rules/no-promise-executor-return.js +205 -204
  246. package/lib/rules/no-proto.js +26 -29
  247. package/lib/rules/no-prototype-builtins.js +146 -124
  248. package/lib/rules/no-redeclare.js +154 -155
  249. package/lib/rules/no-regex-spaces.js +183 -161
  250. package/lib/rules/no-restricted-exports.js +208 -174
  251. package/lib/rules/no-restricted-globals.js +254 -112
  252. package/lib/rules/no-restricted-imports.js +824 -384
  253. package/lib/rules/no-restricted-modules.js +222 -186
  254. package/lib/rules/no-restricted-properties.js +218 -153
  255. package/lib/rules/no-restricted-syntax.js +56 -52
  256. package/lib/rules/no-return-assign.js +56 -49
  257. package/lib/rules/no-return-await.js +147 -120
  258. package/lib/rules/no-script-url.js +53 -46
  259. package/lib/rules/no-self-assign.js +148 -145
  260. package/lib/rules/no-self-compare.js +63 -46
  261. package/lib/rules/no-sequences.js +135 -115
  262. package/lib/rules/no-setter-return.js +176 -178
  263. package/lib/rules/no-shadow-restricted-names.js +84 -36
  264. package/lib/rules/no-shadow.js +598 -310
  265. package/lib/rules/no-spaced-func.js +82 -60
  266. package/lib/rules/no-sparse-arrays.js +46 -28
  267. package/lib/rules/no-sync.js +61 -44
  268. package/lib/rules/no-tabs.js +83 -54
  269. package/lib/rules/no-template-curly-in-string.js +33 -32
  270. package/lib/rules/no-ternary.js +25 -28
  271. package/lib/rules/no-this-before-super.js +332 -298
  272. package/lib/rules/no-throw-literal.js +31 -36
  273. package/lib/rules/no-trailing-spaces.js +208 -174
  274. package/lib/rules/no-unassigned-vars.js +80 -0
  275. package/lib/rules/no-undef-init.js +86 -60
  276. package/lib/rules/no-undef.js +52 -47
  277. package/lib/rules/no-undefined.js +73 -74
  278. package/lib/rules/no-underscore-dangle.js +370 -322
  279. package/lib/rules/no-unexpected-multiline.js +112 -102
  280. package/lib/rules/no-unmodified-loop-condition.js +254 -254
  281. package/lib/rules/no-unneeded-ternary.js +212 -146
  282. package/lib/rules/no-unreachable-loop.js +145 -140
  283. package/lib/rules/no-unreachable.js +255 -248
  284. package/lib/rules/no-unsafe-finally.js +93 -85
  285. package/lib/rules/no-unsafe-negation.js +105 -81
  286. package/lib/rules/no-unsafe-optional-chaining.js +193 -177
  287. package/lib/rules/no-unused-expressions.js +199 -158
  288. package/lib/rules/no-unused-labels.js +139 -124
  289. package/lib/rules/no-unused-private-class-members.js +206 -182
  290. package/lib/rules/no-unused-vars.js +1708 -687
  291. package/lib/rules/no-use-before-define.js +327 -229
  292. package/lib/rules/no-useless-assignment.js +654 -0
  293. package/lib/rules/no-useless-backreference.js +212 -143
  294. package/lib/rules/no-useless-call.js +58 -53
  295. package/lib/rules/no-useless-catch.js +40 -40
  296. package/lib/rules/no-useless-computed-key.js +144 -108
  297. package/lib/rules/no-useless-concat.js +65 -59
  298. package/lib/rules/no-useless-constructor.js +160 -97
  299. package/lib/rules/no-useless-escape.js +364 -291
  300. package/lib/rules/no-useless-rename.js +183 -153
  301. package/lib/rules/no-useless-return.js +344 -307
  302. package/lib/rules/no-var.js +245 -212
  303. package/lib/rules/no-void.js +51 -46
  304. package/lib/rules/no-warning-comments.js +191 -183
  305. package/lib/rules/no-whitespace-before-property.js +131 -97
  306. package/lib/rules/no-with.js +24 -26
  307. package/lib/rules/nonblock-statement-body-position.js +149 -112
  308. package/lib/rules/object-curly-newline.js +306 -247
  309. package/lib/rules/object-curly-spacing.js +360 -296
  310. package/lib/rules/object-property-newline.js +137 -88
  311. package/lib/rules/object-shorthand.js +632 -500
  312. package/lib/rules/one-var-declaration-per-line.js +104 -82
  313. package/lib/rules/one-var.js +686 -536
  314. package/lib/rules/operator-assignment.js +219 -158
  315. package/lib/rules/operator-linebreak.js +295 -233
  316. package/lib/rules/padded-blocks.js +346 -290
  317. package/lib/rules/padding-line-between-statements.js +443 -421
  318. package/lib/rules/prefer-arrow-callback.js +371 -315
  319. package/lib/rules/prefer-const.js +418 -373
  320. package/lib/rules/prefer-destructuring.js +309 -278
  321. package/lib/rules/prefer-exponentiation-operator.js +176 -132
  322. package/lib/rules/prefer-named-capture-group.js +160 -141
  323. package/lib/rules/prefer-numeric-literals.js +121 -112
  324. package/lib/rules/prefer-object-has-own.js +116 -82
  325. package/lib/rules/prefer-object-spread.js +214 -193
  326. package/lib/rules/prefer-promise-reject-errors.js +140 -118
  327. package/lib/rules/prefer-reflect.js +126 -103
  328. package/lib/rules/prefer-regex-literals.js +561 -463
  329. package/lib/rules/prefer-rest-params.js +79 -80
  330. package/lib/rules/prefer-spread.js +47 -43
  331. package/lib/rules/prefer-template.js +266 -194
  332. package/lib/rules/preserve-caught-error.js +535 -0
  333. package/lib/rules/quote-props.js +373 -289
  334. package/lib/rules/quotes.js +374 -308
  335. package/lib/rules/radix.js +152 -134
  336. package/lib/rules/require-atomic-updates.js +316 -282
  337. package/lib/rules/require-await.js +153 -82
  338. package/lib/rules/require-unicode-regexp.js +296 -108
  339. package/lib/rules/require-yield.js +53 -54
  340. package/lib/rules/rest-spread-spacing.js +128 -98
  341. package/lib/rules/semi-spacing.js +281 -232
  342. package/lib/rules/semi-style.js +176 -116
  343. package/lib/rules/semi.js +456 -418
  344. package/lib/rules/sort-imports.js +307 -229
  345. package/lib/rules/sort-keys.js +219 -181
  346. package/lib/rules/sort-vars.js +127 -91
  347. package/lib/rules/space-before-blocks.js +199 -171
  348. package/lib/rules/space-before-function-paren.js +186 -148
  349. package/lib/rules/space-in-parens.js +359 -270
  350. package/lib/rules/space-infix-ops.js +237 -183
  351. package/lib/rules/space-unary-ops.js +356 -280
  352. package/lib/rules/spaced-comment.js +363 -301
  353. package/lib/rules/strict.js +266 -229
  354. package/lib/rules/switch-colon-spacing.js +130 -104
  355. package/lib/rules/symbol-description.js +45 -48
  356. package/lib/rules/template-curly-spacing.js +148 -124
  357. package/lib/rules/template-tag-spacing.js +98 -70
  358. package/lib/rules/unicode-bom.js +54 -54
  359. package/lib/rules/use-isnan.js +237 -110
  360. package/lib/rules/utils/ast-utils.js +2139 -1688
  361. package/lib/rules/utils/char-source.js +247 -0
  362. package/lib/rules/utils/fix-tracker.js +99 -88
  363. package/lib/rules/utils/keywords.js +59 -59
  364. package/lib/rules/utils/lazy-loading-rule-map.js +81 -78
  365. package/lib/rules/utils/regular-expressions.js +35 -19
  366. package/lib/rules/utils/unicode/index.js +9 -4
  367. package/lib/rules/utils/unicode/is-combining-character.js +1 -1
  368. package/lib/rules/utils/unicode/is-emoji-modifier.js +1 -1
  369. package/lib/rules/utils/unicode/is-regional-indicator-symbol.js +1 -1
  370. package/lib/rules/utils/unicode/is-surrogate-pair.js +1 -1
  371. package/lib/rules/valid-typeof.js +153 -109
  372. package/lib/rules/vars-on-top.js +152 -144
  373. package/lib/rules/wrap-iife.js +204 -173
  374. package/lib/rules/wrap-regex.js +77 -47
  375. package/lib/rules/yield-star-spacing.js +145 -116
  376. package/lib/rules/yoda.js +283 -274
  377. package/lib/services/parser-service.js +65 -0
  378. package/lib/services/processor-service.js +101 -0
  379. package/lib/services/suppressions-service.js +302 -0
  380. package/lib/services/warning-service.js +98 -0
  381. package/lib/shared/ajv.js +14 -14
  382. package/lib/shared/assert.js +21 -0
  383. package/lib/shared/ast-utils.js +7 -6
  384. package/lib/shared/deep-merge-arrays.js +62 -0
  385. package/lib/shared/directives.js +3 -2
  386. package/lib/shared/flags.js +108 -0
  387. package/lib/shared/logging.js +24 -16
  388. package/lib/shared/naming.js +109 -0
  389. package/lib/shared/option-utils.js +63 -0
  390. package/lib/shared/relative-module-resolver.js +18 -40
  391. package/lib/shared/runtime-info.js +138 -128
  392. package/lib/shared/serialization.js +78 -0
  393. package/lib/shared/severity.js +22 -22
  394. package/lib/shared/stats.js +30 -0
  395. package/lib/shared/string-utils.js +19 -21
  396. package/lib/shared/text-table.js +68 -0
  397. package/lib/shared/translate-cli-options.js +281 -0
  398. package/lib/shared/traverser.js +153 -146
  399. package/lib/types/config-api.d.ts +12 -0
  400. package/lib/types/index.d.ts +1473 -0
  401. package/lib/types/rules.d.ts +5589 -0
  402. package/lib/types/universal.d.ts +6 -0
  403. package/lib/types/use-at-your-own-risk.d.ts +87 -0
  404. package/lib/universal.js +10 -0
  405. package/lib/unsupported-api.js +8 -9
  406. package/messages/all-files-ignored.js +3 -3
  407. package/messages/all-matched-files-ignored.js +21 -0
  408. package/messages/config-file-missing.js +16 -0
  409. package/messages/config-plugin-missing.js +14 -0
  410. package/messages/config-serialize-function.js +30 -0
  411. package/messages/eslintrc-incompat.js +35 -16
  412. package/messages/eslintrc-plugins.js +8 -5
  413. package/messages/extend-config-missing.js +3 -3
  414. package/messages/failed-to-read-json.js +3 -3
  415. package/messages/file-not-found.js +3 -3
  416. package/messages/invalid-rule-options.js +2 -2
  417. package/messages/invalid-rule-severity.js +2 -2
  418. package/messages/no-config-found.js +4 -4
  419. package/messages/plugin-conflict.js +9 -9
  420. package/messages/plugin-invalid.js +4 -4
  421. package/messages/plugin-missing.js +4 -4
  422. package/messages/print-config-with-directory-path.js +2 -2
  423. package/messages/shared.js +6 -1
  424. package/messages/whitespace-found.js +3 -3
  425. package/package.json +105 -60
  426. package/conf/config-schema.js +0 -93
  427. package/lib/cli-engine/formatters/checkstyle.js +0 -60
  428. package/lib/cli-engine/formatters/compact.js +0 -60
  429. package/lib/cli-engine/formatters/jslint-xml.js +0 -41
  430. package/lib/cli-engine/formatters/junit.js +0 -82
  431. package/lib/cli-engine/formatters/tap.js +0 -95
  432. package/lib/cli-engine/formatters/unix.js +0 -58
  433. package/lib/cli-engine/formatters/visualstudio.js +0 -63
  434. package/lib/cli-engine/xml-escape.js +0 -34
  435. package/lib/config/flat-config-helpers.js +0 -111
  436. package/lib/config/rule-validator.js +0 -158
  437. package/lib/eslint/flat-eslint.js +0 -1159
  438. package/lib/linter/config-comment-parser.js +0 -185
  439. package/lib/linter/node-event-generator.js +0 -354
  440. package/lib/linter/report-translator.js +0 -369
  441. package/lib/linter/safe-emitter.js +0 -52
  442. package/lib/rule-tester/flat-rule-tester.js +0 -1131
  443. package/lib/rules/require-jsdoc.js +0 -122
  444. package/lib/rules/utils/patterns/letters.js +0 -36
  445. package/lib/rules/valid-jsdoc.js +0 -516
  446. package/lib/shared/config-validator.js +0 -347
  447. package/lib/shared/deprecation-warnings.js +0 -58
  448. package/lib/shared/types.js +0 -216
  449. package/lib/source-code/index.js +0 -5
  450. package/lib/source-code/source-code.js +0 -1055
  451. package/lib/source-code/token-store/backward-token-comment-cursor.js +0 -57
  452. package/lib/source-code/token-store/backward-token-cursor.js +0 -58
  453. package/lib/source-code/token-store/cursors.js +0 -90
  454. package/lib/source-code/token-store/forward-token-comment-cursor.js +0 -57
  455. package/lib/source-code/token-store/forward-token-cursor.js +0 -63
  456. package/lib/source-code/token-store/index.js +0 -627
  457. package/lib/source-code/token-store/padded-token-cursor.js +0 -38
  458. package/lib/source-code/token-store/utils.js +0 -107
@@ -0,0 +1,1364 @@
1
+ /**
2
+ * @fileoverview Abstraction of JavaScript source code.
3
+ * @author Nicholas C. Zakas
4
+ */
5
+ "use strict";
6
+
7
+ //------------------------------------------------------------------------------
8
+ // Requirements
9
+ //------------------------------------------------------------------------------
10
+
11
+ const { isCommentToken } = require("@eslint-community/eslint-utils"),
12
+ TokenStore = require("./token-store"),
13
+ astUtils = require("../../../shared/ast-utils"),
14
+ Traverser = require("../../../shared/traverser"),
15
+ globals = require("../../../../conf/globals"),
16
+ { directivesPattern } = require("../../../shared/directives"),
17
+ CodePathAnalyzer = require("../../../linter/code-path-analysis/code-path-analyzer"),
18
+ {
19
+ ConfigCommentParser,
20
+ VisitNodeStep,
21
+ CallMethodStep,
22
+ Directive,
23
+ } = require("@eslint/plugin-kit"),
24
+ eslintScope = require("eslint-scope");
25
+
26
+ //------------------------------------------------------------------------------
27
+ // Type Definitions
28
+ //------------------------------------------------------------------------------
29
+
30
+ /** @typedef {import("eslint-scope").Variable} Variable */
31
+ /** @typedef {import("eslint-scope").Scope} Scope */
32
+ /** @typedef {import("@eslint/core").SourceCode} ISourceCode */
33
+ /** @typedef {import("@eslint/core").Directive} IDirective */
34
+ /** @typedef {import("@eslint/core").TraversalStep} ITraversalStep */
35
+
36
+ //------------------------------------------------------------------------------
37
+ // Private
38
+ //------------------------------------------------------------------------------
39
+
40
+ const commentParser = new ConfigCommentParser();
41
+
42
+ /**
43
+ * Validates that the given AST has the required information.
44
+ * @param {ASTNode} ast The Program node of the AST to check.
45
+ * @throws {TypeError} If the AST doesn't contain the correct information.
46
+ * @returns {void}
47
+ * @private
48
+ */
49
+ function validate(ast) {
50
+ if (!ast) {
51
+ throw new TypeError(`Unexpected empty AST. (${ast})`);
52
+ }
53
+
54
+ if (!ast.tokens) {
55
+ throw new TypeError("AST is missing the tokens array.");
56
+ }
57
+
58
+ if (!ast.comments) {
59
+ throw new TypeError("AST is missing the comments array.");
60
+ }
61
+
62
+ if (!ast.loc) {
63
+ throw new TypeError("AST is missing location information.");
64
+ }
65
+
66
+ if (!ast.range) {
67
+ throw new TypeError("AST is missing range information");
68
+ }
69
+ }
70
+
71
+ /**
72
+ * Retrieves globals for the given ecmaVersion.
73
+ * @param {number} ecmaVersion The version to retrieve globals for.
74
+ * @returns {Object} The globals for the given ecmaVersion.
75
+ */
76
+ function getGlobalsForEcmaVersion(ecmaVersion) {
77
+ switch (ecmaVersion) {
78
+ case 3:
79
+ return globals.es3;
80
+
81
+ case 5:
82
+ return globals.es5;
83
+
84
+ default:
85
+ if (ecmaVersion < 2015) {
86
+ return globals[`es${ecmaVersion + 2009}`];
87
+ }
88
+
89
+ return globals[`es${ecmaVersion}`];
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Check to see if its a ES6 export declaration.
95
+ * @param {ASTNode} astNode An AST node.
96
+ * @returns {boolean} whether the given node represents an export declaration.
97
+ * @private
98
+ */
99
+ function looksLikeExport(astNode) {
100
+ return (
101
+ astNode.type === "ExportDefaultDeclaration" ||
102
+ astNode.type === "ExportNamedDeclaration" ||
103
+ astNode.type === "ExportAllDeclaration" ||
104
+ astNode.type === "ExportSpecifier"
105
+ );
106
+ }
107
+
108
+ /**
109
+ * Merges two sorted lists into a larger sorted list in O(n) time.
110
+ * @param {Token[]} tokens The list of tokens.
111
+ * @param {Token[]} comments The list of comments.
112
+ * @returns {Token[]} A sorted list of tokens and comments.
113
+ * @private
114
+ */
115
+ function sortedMerge(tokens, comments) {
116
+ const result = [];
117
+ let tokenIndex = 0;
118
+ let commentIndex = 0;
119
+
120
+ while (tokenIndex < tokens.length || commentIndex < comments.length) {
121
+ if (
122
+ commentIndex >= comments.length ||
123
+ (tokenIndex < tokens.length &&
124
+ tokens[tokenIndex].range[0] < comments[commentIndex].range[0])
125
+ ) {
126
+ result.push(tokens[tokenIndex++]);
127
+ } else {
128
+ result.push(comments[commentIndex++]);
129
+ }
130
+ }
131
+
132
+ return result;
133
+ }
134
+
135
+ /**
136
+ * Normalizes a value for a global in a config
137
+ * @param {(boolean|string|null)} configuredValue The value given for a global in configuration or in
138
+ * a global directive comment
139
+ * @returns {("readonly"|"writable"|"off")} The value normalized as a string
140
+ * @throws {Error} if global value is invalid
141
+ */
142
+ function normalizeConfigGlobal(configuredValue) {
143
+ switch (configuredValue) {
144
+ case "off":
145
+ return "off";
146
+
147
+ case true:
148
+ case "true":
149
+ case "writeable":
150
+ case "writable":
151
+ return "writable";
152
+
153
+ case null:
154
+ case false:
155
+ case "false":
156
+ case "readable":
157
+ case "readonly":
158
+ return "readonly";
159
+
160
+ default:
161
+ throw new Error(
162
+ `'${configuredValue}' is not a valid configuration for a global (use 'readonly', 'writable', or 'off')`,
163
+ );
164
+ }
165
+ }
166
+
167
+ /**
168
+ * Determines if two nodes or tokens overlap.
169
+ * @param {ASTNode|Token} first The first node or token to check.
170
+ * @param {ASTNode|Token} second The second node or token to check.
171
+ * @returns {boolean} True if the two nodes or tokens overlap.
172
+ * @private
173
+ */
174
+ function nodesOrTokensOverlap(first, second) {
175
+ return (
176
+ (first.range[0] <= second.range[0] &&
177
+ first.range[1] >= second.range[0]) ||
178
+ (second.range[0] <= first.range[0] && second.range[1] >= first.range[0])
179
+ );
180
+ }
181
+
182
+ /**
183
+ * Determines if two nodes or tokens have at least one whitespace character
184
+ * between them. Order does not matter. Returns false if the given nodes or
185
+ * tokens overlap.
186
+ * @param {SourceCode} sourceCode The source code object.
187
+ * @param {ASTNode|Token} first The first node or token to check between.
188
+ * @param {ASTNode|Token} second The second node or token to check between.
189
+ * @param {boolean} checkInsideOfJSXText If `true` is present, check inside of JSXText tokens for backward compatibility.
190
+ * @returns {boolean} True if there is a whitespace character between
191
+ * any of the tokens found between the two given nodes or tokens.
192
+ * @public
193
+ */
194
+ function isSpaceBetween(sourceCode, first, second, checkInsideOfJSXText) {
195
+ if (nodesOrTokensOverlap(first, second)) {
196
+ return false;
197
+ }
198
+
199
+ const [startingNodeOrToken, endingNodeOrToken] =
200
+ first.range[1] <= second.range[0] ? [first, second] : [second, first];
201
+ const firstToken =
202
+ sourceCode.getLastToken(startingNodeOrToken) || startingNodeOrToken;
203
+ const finalToken =
204
+ sourceCode.getFirstToken(endingNodeOrToken) || endingNodeOrToken;
205
+ let currentToken = firstToken;
206
+
207
+ while (currentToken !== finalToken) {
208
+ const nextToken = sourceCode.getTokenAfter(currentToken, {
209
+ includeComments: true,
210
+ });
211
+
212
+ if (
213
+ currentToken.range[1] !== nextToken.range[0] ||
214
+ /*
215
+ * For backward compatibility, check spaces in JSXText.
216
+ * https://github.com/eslint/eslint/issues/12614
217
+ */
218
+ (checkInsideOfJSXText &&
219
+ nextToken !== finalToken &&
220
+ nextToken.type === "JSXText" &&
221
+ /\s/u.test(nextToken.value))
222
+ ) {
223
+ return true;
224
+ }
225
+
226
+ currentToken = nextToken;
227
+ }
228
+
229
+ return false;
230
+ }
231
+
232
+ /**
233
+ * Performs binary search to find the line number containing a given character index.
234
+ * Returns the lower bound - the index of the first element greater than the target.
235
+ * **Please note that the `lineStartIndices` should be sorted in ascending order**.
236
+ * - Time Complexity: O(log n) - Significantly faster than linear search for large files.
237
+ * @param {number[]} lineStartIndices Sorted array of line start indices.
238
+ * @param {number} target The character index to find the line number for.
239
+ * @returns {number} The 1-based line number for the target index.
240
+ * @private
241
+ */
242
+ function findLineNumberBinarySearch(lineStartIndices, target) {
243
+ let low = 0;
244
+ let high = lineStartIndices.length;
245
+
246
+ while (low < high) {
247
+ const mid = ((low + high) / 2) | 0; // Use bitwise OR to floor the division
248
+
249
+ if (target < lineStartIndices[mid]) {
250
+ high = mid;
251
+ } else {
252
+ low = mid + 1;
253
+ }
254
+ }
255
+
256
+ return low;
257
+ }
258
+
259
+ //-----------------------------------------------------------------------------
260
+ // Directive Comments
261
+ //-----------------------------------------------------------------------------
262
+
263
+ /**
264
+ * Ensures that variables representing built-in properties of the Global Object,
265
+ * and any globals declared by special block comments, are present in the global
266
+ * scope.
267
+ * @param {Scope} globalScope The global scope.
268
+ * @param {Object|undefined} configGlobals The globals declared in configuration
269
+ * @param {Object|undefined} inlineGlobals The globals declared in the source code
270
+ * @returns {void}
271
+ */
272
+ function addDeclaredGlobals(
273
+ globalScope,
274
+ configGlobals = {},
275
+ inlineGlobals = {},
276
+ ) {
277
+ // Define configured global variables.
278
+ for (const id of new Set([
279
+ ...Object.keys(configGlobals),
280
+ ...Object.keys(inlineGlobals),
281
+ ])) {
282
+ /*
283
+ * `normalizeConfigGlobal` will throw an error if a configured global value is invalid. However, these errors would
284
+ * typically be caught when validating a config anyway (validity for inline global comments is checked separately).
285
+ */
286
+ const configValue =
287
+ configGlobals[id] === void 0
288
+ ? void 0
289
+ : normalizeConfigGlobal(configGlobals[id]);
290
+ const commentValue = inlineGlobals[id] && inlineGlobals[id].value;
291
+ const value = commentValue || configValue;
292
+ const sourceComments = inlineGlobals[id] && inlineGlobals[id].comments;
293
+
294
+ if (value === "off") {
295
+ continue;
296
+ }
297
+
298
+ let variable = globalScope.set.get(id);
299
+
300
+ if (!variable) {
301
+ variable = new eslintScope.Variable(id, globalScope);
302
+
303
+ globalScope.variables.push(variable);
304
+ globalScope.set.set(id, variable);
305
+ }
306
+
307
+ variable.eslintImplicitGlobalSetting = configValue;
308
+ variable.eslintExplicitGlobal = sourceComments !== void 0;
309
+ variable.eslintExplicitGlobalComments = sourceComments;
310
+ variable.writeable = value === "writable";
311
+ }
312
+
313
+ /*
314
+ * "through" contains all references which definitions cannot be found.
315
+ * Since we augment the global scope using configuration, we need to update
316
+ * references and remove the ones that were added by configuration.
317
+ */
318
+ globalScope.through = globalScope.through.filter(reference => {
319
+ const name = reference.identifier.name;
320
+ const variable = globalScope.set.get(name);
321
+
322
+ if (variable) {
323
+ /*
324
+ * Links the variable and the reference.
325
+ * And this reference is removed from `Scope#through`.
326
+ */
327
+ reference.resolved = variable;
328
+ variable.references.push(reference);
329
+
330
+ return false;
331
+ }
332
+
333
+ return true;
334
+ });
335
+
336
+ /*
337
+ * "implicit" contains information about implicit global variables (those created
338
+ * implicitly by assigning values to undeclared variables in non-strict code).
339
+ * Since we augment the global scope using configuration, we need to remove
340
+ * the ones that were added by configuration, as they are either built-in
341
+ * or declared elsewhere, therefore not implicit.
342
+ * Since the "implicit" property was not documented, first we'll check if it exists
343
+ * because it's possible that not all custom scope managers create this property.
344
+ * If it exists, we assume it has properties `variables` and `set`. Property
345
+ * `left` is considered optional (for example, typescript-eslint's scope manage
346
+ * has this property named `leftToBeResolved`).
347
+ */
348
+ const { implicit } = globalScope;
349
+ if (typeof implicit === "object" && implicit !== null) {
350
+ implicit.variables = implicit.variables.filter(variable => {
351
+ const name = variable.name;
352
+ if (globalScope.set.has(name)) {
353
+ implicit.set.delete(name);
354
+ return false;
355
+ }
356
+ return true;
357
+ });
358
+
359
+ if (implicit.left) {
360
+ implicit.left = implicit.left.filter(
361
+ reference => !globalScope.set.has(reference.identifier.name),
362
+ );
363
+ }
364
+ }
365
+ }
366
+
367
+ /**
368
+ * Sets the given variable names as exported so they won't be triggered by
369
+ * the `no-unused-vars` rule.
370
+ * @param {eslint.Scope} globalScope The global scope to define exports in.
371
+ * @param {Record<string,string>} variables An object whose keys are the variable
372
+ * names to export.
373
+ * @returns {void}
374
+ */
375
+ function markExportedVariables(globalScope, variables) {
376
+ Object.keys(variables).forEach(name => {
377
+ const variable = globalScope.set.get(name);
378
+
379
+ if (variable) {
380
+ variable.eslintUsed = true;
381
+ variable.eslintExported = true;
382
+ }
383
+ });
384
+ }
385
+
386
+ //------------------------------------------------------------------------------
387
+ // Public Interface
388
+ //------------------------------------------------------------------------------
389
+
390
+ const caches = Symbol("caches");
391
+
392
+ /**
393
+ * Represents parsed source code.
394
+ * @implements {ISourceCode}
395
+ */
396
+ class SourceCode extends TokenStore {
397
+ /**
398
+ * The cache of steps that were taken while traversing the source code.
399
+ * @type {Array<ITraversalStep>}
400
+ */
401
+ #steps;
402
+
403
+ /**
404
+ * Creates a new instance.
405
+ * @param {string|Object} textOrConfig The source code text or config object.
406
+ * @param {string} textOrConfig.text The source code text.
407
+ * @param {ASTNode} textOrConfig.ast The Program node of the AST representing the code. This AST should be created from the text that BOM was stripped.
408
+ * @param {boolean} textOrConfig.hasBOM Indicates if the text has a Unicode BOM.
409
+ * @param {Object|null} textOrConfig.parserServices The parser services.
410
+ * @param {ScopeManager|null} textOrConfig.scopeManager The scope of this source code.
411
+ * @param {Object|null} textOrConfig.visitorKeys The visitor keys to traverse AST.
412
+ * @param {ASTNode} [astIfNoConfig] The Program node of the AST representing the code. This AST should be created from the text that BOM was stripped.
413
+ */
414
+ constructor(textOrConfig, astIfNoConfig) {
415
+ let text, hasBOM, ast, parserServices, scopeManager, visitorKeys;
416
+
417
+ // Process overloading of arguments
418
+ if (typeof textOrConfig === "string") {
419
+ text = textOrConfig;
420
+ ast = astIfNoConfig;
421
+ hasBOM = false;
422
+ } else if (typeof textOrConfig === "object" && textOrConfig !== null) {
423
+ text = textOrConfig.text;
424
+ ast = textOrConfig.ast;
425
+ hasBOM = textOrConfig.hasBOM;
426
+ parserServices = textOrConfig.parserServices;
427
+ scopeManager = textOrConfig.scopeManager;
428
+ visitorKeys = textOrConfig.visitorKeys;
429
+ }
430
+
431
+ validate(ast);
432
+ super(ast.tokens, ast.comments);
433
+
434
+ /**
435
+ * General purpose caching for the class.
436
+ */
437
+ this[caches] = new Map([
438
+ ["scopes", new WeakMap()],
439
+ ["vars", new Map()],
440
+ ["configNodes", void 0],
441
+ ["isGlobalReference", new WeakMap()],
442
+ ]);
443
+
444
+ /**
445
+ * Indicates if the AST is ESTree compatible.
446
+ * @type {boolean}
447
+ */
448
+ this.isESTree = ast.type === "Program";
449
+
450
+ /*
451
+ * Backwards compatibility for BOM handling.
452
+ *
453
+ * The `hasBOM` property has been available on the `SourceCode` object
454
+ * for a long time and is used to indicate if the source contains a BOM.
455
+ * The linter strips the BOM and just passes the `hasBOM` property to the
456
+ * `SourceCode` constructor to make it easier for languages to not deal with
457
+ * the BOM.
458
+ *
459
+ * However, the text passed in to the `SourceCode` constructor might still
460
+ * have a BOM if the constructor is called outside of the linter, so we still
461
+ * need to check for the BOM in the text.
462
+ */
463
+ const textHasBOM = text.charCodeAt(0) === 0xfeff;
464
+
465
+ /**
466
+ * The flag to indicate that the source code has Unicode BOM.
467
+ * @type {boolean}
468
+ */
469
+ this.hasBOM = textHasBOM || !!hasBOM;
470
+
471
+ /**
472
+ * The original text source code.
473
+ * BOM was stripped from this text.
474
+ * @type {string}
475
+ */
476
+ this.text = textHasBOM ? text.slice(1) : text;
477
+
478
+ /**
479
+ * The parsed AST for the source code.
480
+ * @type {ASTNode}
481
+ */
482
+ this.ast = ast;
483
+
484
+ /**
485
+ * The parser services of this source code.
486
+ * @type {Object}
487
+ */
488
+ this.parserServices = parserServices || {};
489
+
490
+ /**
491
+ * The scope of this source code.
492
+ * @type {ScopeManager|null}
493
+ */
494
+ this.scopeManager = scopeManager || null;
495
+
496
+ /**
497
+ * The visitor keys to traverse AST.
498
+ * @type {Object}
499
+ */
500
+ this.visitorKeys = visitorKeys || Traverser.DEFAULT_VISITOR_KEYS;
501
+
502
+ // Check the source text for the presence of a shebang since it is parsed as a standard line comment.
503
+ const shebangMatched = this.text.match(astUtils.shebangPattern);
504
+ const hasShebang =
505
+ shebangMatched &&
506
+ ast.comments.length &&
507
+ ast.comments[0].value === shebangMatched[1];
508
+
509
+ if (hasShebang) {
510
+ ast.comments[0].type = "Shebang";
511
+ }
512
+
513
+ this.tokensAndComments = sortedMerge(ast.tokens, ast.comments);
514
+
515
+ /**
516
+ * The source code split into lines according to ECMA-262 specification.
517
+ * This is done to avoid each rule needing to do so separately.
518
+ * @type {string[]}
519
+ */
520
+ this.lines = [];
521
+
522
+ /**
523
+ * @type {number[]}
524
+ */
525
+ this.lineStartIndices = [0];
526
+
527
+ const lineEndingPattern = astUtils.createGlobalLinebreakMatcher();
528
+ let match;
529
+
530
+ /*
531
+ * Previously, this was implemented using a regex that
532
+ * matched a sequence of non-linebreak characters followed by a
533
+ * linebreak, then adding the lengths of the matches. However,
534
+ * this caused a catastrophic backtracking issue when the end
535
+ * of a file contained a large number of non-newline characters.
536
+ * To avoid this, the current implementation just matches newlines
537
+ * and uses match.index to get the correct line start indices.
538
+ */
539
+ while ((match = lineEndingPattern.exec(this.text))) {
540
+ this.lines.push(
541
+ this.text.slice(this.lineStartIndices.at(-1), match.index),
542
+ );
543
+ this.lineStartIndices.push(match.index + match[0].length);
544
+ }
545
+ this.lines.push(this.text.slice(this.lineStartIndices.at(-1)));
546
+
547
+ // don't allow further modification of this object
548
+ Object.freeze(this);
549
+ Object.freeze(this.lines);
550
+ }
551
+
552
+ /**
553
+ * Split the source code into multiple lines based on the line delimiters.
554
+ * @param {string} text Source code as a string.
555
+ * @returns {string[]} Array of source code lines.
556
+ * @public
557
+ */
558
+ static splitLines(text) {
559
+ return text.split(astUtils.createGlobalLinebreakMatcher());
560
+ }
561
+
562
+ /**
563
+ * Gets the source code for the given node.
564
+ * @param {ASTNode} [node] The AST node to get the text for.
565
+ * @param {number} [beforeCount] The number of characters before the node to retrieve.
566
+ * @param {number} [afterCount] The number of characters after the node to retrieve.
567
+ * @returns {string} The text representing the AST node.
568
+ * @public
569
+ */
570
+ getText(node, beforeCount, afterCount) {
571
+ if (node) {
572
+ return this.text.slice(
573
+ Math.max(node.range[0] - (beforeCount || 0), 0),
574
+ node.range[1] + (afterCount || 0),
575
+ );
576
+ }
577
+ return this.text;
578
+ }
579
+
580
+ /**
581
+ * Gets the entire source text split into an array of lines.
582
+ * @returns {string[]} The source text as an array of lines.
583
+ * @public
584
+ */
585
+ getLines() {
586
+ return this.lines;
587
+ }
588
+
589
+ /**
590
+ * Retrieves an array containing all comments in the source code.
591
+ * @returns {ASTNode[]} An array of comment nodes.
592
+ * @public
593
+ */
594
+ getAllComments() {
595
+ return this.ast.comments;
596
+ }
597
+
598
+ /**
599
+ * Retrieves the JSDoc comment for a given node.
600
+ * @param {ASTNode} node The AST node to get the comment for.
601
+ * @returns {Token|null} The Block comment token containing the JSDoc comment
602
+ * for the given node or null if not found.
603
+ * @public
604
+ * @deprecated
605
+ */
606
+ getJSDocComment(node) {
607
+ /**
608
+ * Checks for the presence of a JSDoc comment for the given node and returns it.
609
+ * @param {ASTNode} astNode The AST node to get the comment for.
610
+ * @returns {Token|null} The Block comment token containing the JSDoc comment
611
+ * for the given node or null if not found.
612
+ * @private
613
+ */
614
+ const findJSDocComment = astNode => {
615
+ const tokenBefore = this.getTokenBefore(astNode, {
616
+ includeComments: true,
617
+ });
618
+
619
+ if (
620
+ tokenBefore &&
621
+ isCommentToken(tokenBefore) &&
622
+ tokenBefore.type === "Block" &&
623
+ tokenBefore.value.charAt(0) === "*" &&
624
+ astNode.loc.start.line - tokenBefore.loc.end.line <= 1
625
+ ) {
626
+ return tokenBefore;
627
+ }
628
+
629
+ return null;
630
+ };
631
+ let parent = node.parent;
632
+
633
+ switch (node.type) {
634
+ case "ClassDeclaration":
635
+ case "FunctionDeclaration":
636
+ return findJSDocComment(
637
+ looksLikeExport(parent) ? parent : node,
638
+ );
639
+
640
+ case "ClassExpression":
641
+ return findJSDocComment(parent.parent);
642
+
643
+ case "ArrowFunctionExpression":
644
+ case "FunctionExpression":
645
+ if (
646
+ parent.type !== "CallExpression" &&
647
+ parent.type !== "NewExpression"
648
+ ) {
649
+ while (
650
+ !this.getCommentsBefore(parent).length &&
651
+ !/Function/u.test(parent.type) &&
652
+ parent.type !== "MethodDefinition" &&
653
+ parent.type !== "Property"
654
+ ) {
655
+ parent = parent.parent;
656
+
657
+ if (!parent) {
658
+ break;
659
+ }
660
+ }
661
+
662
+ if (
663
+ parent &&
664
+ parent.type !== "FunctionDeclaration" &&
665
+ parent.type !== "Program"
666
+ ) {
667
+ return findJSDocComment(parent);
668
+ }
669
+ }
670
+
671
+ return findJSDocComment(node);
672
+
673
+ // falls through
674
+ default:
675
+ return null;
676
+ }
677
+ }
678
+
679
+ /**
680
+ * Gets the deepest node containing a range index.
681
+ * @param {number} index Range index of the desired node.
682
+ * @returns {ASTNode} The node if found or null if not found.
683
+ * @public
684
+ */
685
+ getNodeByRangeIndex(index) {
686
+ let result = null;
687
+
688
+ Traverser.traverse(this.ast, {
689
+ visitorKeys: this.visitorKeys,
690
+ enter(node) {
691
+ if (node.range[0] <= index && index < node.range[1]) {
692
+ result = node;
693
+ } else {
694
+ this.skip();
695
+ }
696
+ },
697
+ leave(node) {
698
+ if (node === result) {
699
+ this.break();
700
+ }
701
+ },
702
+ });
703
+
704
+ return result;
705
+ }
706
+
707
+ /**
708
+ * Determines if two nodes or tokens have at least one whitespace character
709
+ * between them. Order does not matter. Returns false if the given nodes or
710
+ * tokens overlap.
711
+ * @param {ASTNode|Token} first The first node or token to check between.
712
+ * @param {ASTNode|Token} second The second node or token to check between.
713
+ * @returns {boolean} True if there is a whitespace character between
714
+ * any of the tokens found between the two given nodes or tokens.
715
+ * @public
716
+ */
717
+ isSpaceBetween(first, second) {
718
+ return isSpaceBetween(this, first, second, false);
719
+ }
720
+
721
+ /**
722
+ * Determines if two nodes or tokens have at least one whitespace character
723
+ * between them. Order does not matter. Returns false if the given nodes or
724
+ * tokens overlap.
725
+ * For backward compatibility, this method returns true if there are
726
+ * `JSXText` tokens that contain whitespaces between the two.
727
+ * @param {ASTNode|Token} first The first node or token to check between.
728
+ * @param {ASTNode|Token} second The second node or token to check between.
729
+ * @returns {boolean} True if there is a whitespace character between
730
+ * any of the tokens found between the two given nodes or tokens.
731
+ * @deprecated in favor of isSpaceBetween().
732
+ * @public
733
+ */
734
+ isSpaceBetweenTokens(first, second) {
735
+ return isSpaceBetween(this, first, second, true);
736
+ }
737
+
738
+ /**
739
+ * Converts a source text index into a (line, column) pair.
740
+ * @param {number} index The index of a character in a file.
741
+ * @throws {TypeError|RangeError} If non-numeric index or index out of range.
742
+ * @returns {{line: number, column: number}} A {line, column} location object with 1-indexed line and 0-indexed column.
743
+ * @public
744
+ */
745
+ getLocFromIndex(index) {
746
+ if (typeof index !== "number") {
747
+ throw new TypeError("Expected `index` to be a number.");
748
+ }
749
+
750
+ if (index < 0 || index > this.text.length) {
751
+ throw new RangeError(
752
+ `Index out of range (requested index ${index}, but source text has length ${this.text.length}).`,
753
+ );
754
+ }
755
+
756
+ /*
757
+ * For an argument of this.text.length, return the location one "spot" past the last character
758
+ * of the file. If the last character is a linebreak, the location will be column 0 of the next
759
+ * line; otherwise, the location will be in the next column on the same line.
760
+ *
761
+ * See getIndexFromLoc for the motivation for this special case.
762
+ */
763
+ if (index === this.text.length) {
764
+ return {
765
+ line: this.lines.length,
766
+ column: this.lines.at(-1).length,
767
+ };
768
+ }
769
+
770
+ /*
771
+ * To figure out which line index is on, determine the last place at which index could
772
+ * be inserted into lineStartIndices to keep the list sorted.
773
+ */
774
+ const lineNumber =
775
+ index >= this.lineStartIndices.at(-1)
776
+ ? this.lineStartIndices.length
777
+ : findLineNumberBinarySearch(this.lineStartIndices, index);
778
+
779
+ return {
780
+ line: lineNumber,
781
+ column: index - this.lineStartIndices[lineNumber - 1],
782
+ };
783
+ }
784
+
785
+ /**
786
+ * Converts a (line, column) pair into a range index.
787
+ * @param {Object} loc A line/column location
788
+ * @param {number} loc.line The line number of the location (1-indexed)
789
+ * @param {number} loc.column The column number of the location (0-indexed)
790
+ * @throws {TypeError|RangeError} If `loc` is not an object with a numeric
791
+ * `line` and `column`, if the `line` is less than or equal to zero or
792
+ * the line or column is out of the expected range.
793
+ * @returns {number} The range index of the location in the file.
794
+ * @public
795
+ */
796
+ getIndexFromLoc(loc) {
797
+ if (
798
+ loc === null ||
799
+ typeof loc !== "object" ||
800
+ typeof loc.line !== "number" ||
801
+ typeof loc.column !== "number"
802
+ ) {
803
+ throw new TypeError(
804
+ "Expected `loc` to be an object with numeric `line` and `column` properties.",
805
+ );
806
+ }
807
+
808
+ if (loc.line <= 0) {
809
+ throw new RangeError(
810
+ `Line number out of range (line ${loc.line} requested). Line numbers should be 1-based.`,
811
+ );
812
+ }
813
+
814
+ if (loc.line > this.lineStartIndices.length) {
815
+ throw new RangeError(
816
+ `Line number out of range (line ${loc.line} requested, but only ${this.lineStartIndices.length} lines present).`,
817
+ );
818
+ }
819
+
820
+ if (loc.column < 0) {
821
+ throw new RangeError(
822
+ `Invalid column number (column ${loc.column} requested).`,
823
+ );
824
+ }
825
+
826
+ const lineStartIndex = this.lineStartIndices[loc.line - 1];
827
+ const lineEndIndex =
828
+ loc.line === this.lineStartIndices.length
829
+ ? this.text.length
830
+ : this.lineStartIndices[loc.line];
831
+ const positionIndex = lineStartIndex + loc.column;
832
+
833
+ /*
834
+ * By design, getIndexFromLoc({ line: lineNum, column: 0 }) should return the start index of
835
+ * the given line, provided that the line number is valid element of this.lines. Since the
836
+ * last element of this.lines is an empty string for files with trailing newlines, add a
837
+ * special case where getting the index for the first location after the end of the file
838
+ * will return the length of the file, rather than throwing an error. This allows rules to
839
+ * use getIndexFromLoc consistently without worrying about edge cases at the end of a file.
840
+ */
841
+ if (
842
+ (loc.line === this.lineStartIndices.length &&
843
+ positionIndex > lineEndIndex) ||
844
+ (loc.line < this.lineStartIndices.length &&
845
+ positionIndex >= lineEndIndex)
846
+ ) {
847
+ throw new RangeError(
848
+ `Column number out of range (column ${loc.column} requested, but the length of line ${loc.line} is ${lineEndIndex - lineStartIndex}).`,
849
+ );
850
+ }
851
+
852
+ return positionIndex;
853
+ }
854
+
855
+ /**
856
+ * Gets the scope for the given node
857
+ * @param {ASTNode} currentNode The node to get the scope of
858
+ * @returns {Scope} The scope information for this node
859
+ * @throws {TypeError} If the `currentNode` argument is missing.
860
+ */
861
+ getScope(currentNode) {
862
+ if (!currentNode) {
863
+ throw new TypeError("Missing required argument: node.");
864
+ }
865
+
866
+ // check cache first
867
+ const cache = this[caches].get("scopes");
868
+ const cachedScope = cache.get(currentNode);
869
+
870
+ if (cachedScope) {
871
+ return cachedScope;
872
+ }
873
+
874
+ // On Program node, get the outermost scope to avoid return Node.js special function scope or ES modules scope.
875
+ const inner = currentNode.type !== "Program";
876
+
877
+ for (let node = currentNode; node; node = node.parent) {
878
+ const scope = this.scopeManager.acquire(node, inner);
879
+
880
+ if (scope) {
881
+ if (scope.type === "function-expression-name") {
882
+ cache.set(currentNode, scope.childScopes[0]);
883
+ return scope.childScopes[0];
884
+ }
885
+
886
+ cache.set(currentNode, scope);
887
+ return scope;
888
+ }
889
+ }
890
+
891
+ cache.set(currentNode, this.scopeManager.scopes[0]);
892
+ return this.scopeManager.scopes[0];
893
+ }
894
+
895
+ /**
896
+ * Get the variables that `node` defines.
897
+ * This is a convenience method that passes through
898
+ * to the same method on the `scopeManager`.
899
+ * @param {ASTNode} node The node for which the variables are obtained.
900
+ * @returns {Array<Variable>} An array of variable nodes representing
901
+ * the variables that `node` defines.
902
+ */
903
+ getDeclaredVariables(node) {
904
+ return this.scopeManager.getDeclaredVariables(node);
905
+ }
906
+
907
+ /* eslint-disable class-methods-use-this -- node is owned by SourceCode */
908
+ /**
909
+ * Gets all the ancestors of a given node
910
+ * @param {ASTNode} node The node
911
+ * @returns {Array<ASTNode>} All the ancestor nodes in the AST, not including the provided node, starting
912
+ * from the root node at index 0 and going inwards to the parent node.
913
+ * @throws {TypeError} When `node` is missing.
914
+ */
915
+ getAncestors(node) {
916
+ if (!node) {
917
+ throw new TypeError("Missing required argument: node.");
918
+ }
919
+
920
+ const ancestorsStartingAtParent = [];
921
+
922
+ for (let ancestor = node.parent; ancestor; ancestor = ancestor.parent) {
923
+ ancestorsStartingAtParent.push(ancestor);
924
+ }
925
+
926
+ return ancestorsStartingAtParent.reverse();
927
+ }
928
+
929
+ /**
930
+ * Determines whether the given identifier node is a reference to a global variable.
931
+ * @param {ASTNode} node `Identifier` node to check.
932
+ * @returns {boolean} True if the identifier is a reference to a global variable.
933
+ */
934
+ isGlobalReference(node) {
935
+ if (!node) {
936
+ throw new TypeError("Missing required argument: node.");
937
+ }
938
+
939
+ const cache = this[caches].get("isGlobalReference");
940
+
941
+ if (cache.has(node)) {
942
+ return cache.get(node);
943
+ }
944
+
945
+ if (node.type !== "Identifier") {
946
+ cache.set(node, false);
947
+ return false;
948
+ }
949
+
950
+ const variable = this.scopeManager.scopes[0].set.get(node.name);
951
+
952
+ if (!variable || variable.defs.length > 0) {
953
+ cache.set(node, false);
954
+ return false;
955
+ }
956
+
957
+ const result = variable.references.some(
958
+ ({ identifier }) => identifier === node,
959
+ );
960
+ cache.set(node, result);
961
+ return result;
962
+ }
963
+
964
+ /**
965
+ * Returns the location of the given node or token.
966
+ * @param {ASTNode|Token} nodeOrToken The node or token to get the location of.
967
+ * @returns {SourceLocation} The location of the node or token.
968
+ */
969
+ getLoc(nodeOrToken) {
970
+ return nodeOrToken.loc;
971
+ }
972
+
973
+ /**
974
+ * Returns the range of the given node or token.
975
+ * @param {ASTNode|Token} nodeOrToken The node or token to get the range of.
976
+ * @returns {[number, number]} The range of the node or token.
977
+ */
978
+ getRange(nodeOrToken) {
979
+ return nodeOrToken.range;
980
+ }
981
+
982
+ /* eslint-enable class-methods-use-this -- node is owned by SourceCode */
983
+
984
+ /**
985
+ * Marks a variable as used in the current scope
986
+ * @param {string} name The name of the variable to mark as used.
987
+ * @param {ASTNode} [refNode] The closest node to the variable reference.
988
+ * @returns {boolean} True if the variable was found and marked as used, false if not.
989
+ */
990
+ markVariableAsUsed(name, refNode = this.ast) {
991
+ const currentScope = this.getScope(refNode);
992
+ let initialScope = currentScope;
993
+
994
+ /*
995
+ * When we are in an ESM or CommonJS module, we need to start searching
996
+ * from the top-level scope, not the global scope. For ESM the top-level
997
+ * scope is the module scope; for CommonJS the top-level scope is the
998
+ * outer function scope.
999
+ *
1000
+ * Without this check, we might miss a variable declared with `var` at
1001
+ * the top-level because it won't exist in the global scope.
1002
+ */
1003
+ if (
1004
+ currentScope.type === "global" &&
1005
+ currentScope.childScopes.length > 0 &&
1006
+ // top-level scopes refer to a `Program` node
1007
+ currentScope.childScopes[0].block === this.ast
1008
+ ) {
1009
+ initialScope = currentScope.childScopes[0];
1010
+ }
1011
+
1012
+ for (let scope = initialScope; scope; scope = scope.upper) {
1013
+ const variable = scope.variables.find(
1014
+ scopeVar => scopeVar.name === name,
1015
+ );
1016
+
1017
+ if (variable) {
1018
+ variable.eslintUsed = true;
1019
+ return true;
1020
+ }
1021
+ }
1022
+
1023
+ return false;
1024
+ }
1025
+
1026
+ /**
1027
+ * Returns an array of all inline configuration nodes found in the
1028
+ * source code.
1029
+ * @returns {Array<Token>} An array of all inline configuration nodes.
1030
+ */
1031
+ getInlineConfigNodes() {
1032
+ // check the cache first
1033
+ let configNodes = this[caches].get("configNodes");
1034
+
1035
+ if (configNodes) {
1036
+ return configNodes;
1037
+ }
1038
+
1039
+ // calculate fresh config nodes
1040
+ configNodes = this.ast.comments.filter(comment => {
1041
+ // shebang comments are never directives
1042
+ if (comment.type === "Shebang") {
1043
+ return false;
1044
+ }
1045
+
1046
+ const directive = commentParser.parseDirective(comment.value);
1047
+
1048
+ if (!directive) {
1049
+ return false;
1050
+ }
1051
+
1052
+ if (!directivesPattern.test(directive.label)) {
1053
+ return false;
1054
+ }
1055
+
1056
+ // only certain comment types are supported as line comments
1057
+ return (
1058
+ comment.type !== "Line" ||
1059
+ !!/^eslint-disable-(?:next-)?line$/u.test(directive.label)
1060
+ );
1061
+ });
1062
+
1063
+ this[caches].set("configNodes", configNodes);
1064
+
1065
+ return configNodes;
1066
+ }
1067
+
1068
+ /**
1069
+ * Returns an all directive nodes that enable or disable rules along with any problems
1070
+ * encountered while parsing the directives.
1071
+ * @returns {{problems:Array<Problem>,directives:Array<Directive>}} Information
1072
+ * that ESLint needs to further process the directives.
1073
+ */
1074
+ getDisableDirectives() {
1075
+ // check the cache first
1076
+ const cachedDirectives = this[caches].get("disableDirectives");
1077
+
1078
+ if (cachedDirectives) {
1079
+ return cachedDirectives;
1080
+ }
1081
+
1082
+ const problems = [];
1083
+ const directives = [];
1084
+
1085
+ this.getInlineConfigNodes().forEach(comment => {
1086
+ // Step 1: Parse the directive
1087
+ const {
1088
+ label,
1089
+ value,
1090
+ justification: justificationPart,
1091
+ } = commentParser.parseDirective(comment.value);
1092
+
1093
+ // Step 2: Extract the directive value
1094
+ const lineCommentSupported =
1095
+ /^eslint-disable-(?:next-)?line$/u.test(label);
1096
+
1097
+ if (comment.type === "Line" && !lineCommentSupported) {
1098
+ return;
1099
+ }
1100
+
1101
+ // Step 3: Validate the directive does not span multiple lines
1102
+ if (
1103
+ label === "eslint-disable-line" &&
1104
+ comment.loc.start.line !== comment.loc.end.line
1105
+ ) {
1106
+ const message = `${label} comment should not span multiple lines.`;
1107
+
1108
+ problems.push({
1109
+ ruleId: null,
1110
+ message,
1111
+ loc: comment.loc,
1112
+ });
1113
+ return;
1114
+ }
1115
+
1116
+ // Step 4: Extract the directive value and create the Directive object
1117
+ switch (label) {
1118
+ case "eslint-disable":
1119
+ case "eslint-enable":
1120
+ case "eslint-disable-next-line":
1121
+ case "eslint-disable-line": {
1122
+ const directiveType = label.slice("eslint-".length);
1123
+
1124
+ directives.push(
1125
+ new Directive({
1126
+ type: directiveType,
1127
+ node: comment,
1128
+ value,
1129
+ justification: justificationPart,
1130
+ }),
1131
+ );
1132
+ }
1133
+
1134
+ // no default
1135
+ }
1136
+ });
1137
+
1138
+ const result = { problems, directives };
1139
+
1140
+ this[caches].set("disableDirectives", result);
1141
+
1142
+ return result;
1143
+ }
1144
+
1145
+ /**
1146
+ * Applies language options sent in from the core.
1147
+ * @param {Object} languageOptions The language options for this run.
1148
+ * @returns {void}
1149
+ */
1150
+ applyLanguageOptions(languageOptions) {
1151
+ /*
1152
+ * Add configured globals and language globals
1153
+ *
1154
+ * Using Object.assign instead of object spread for performance reasons
1155
+ * https://github.com/eslint/eslint/issues/16302
1156
+ */
1157
+ const configGlobals = Object.assign(
1158
+ Object.create(null), // https://github.com/eslint/eslint/issues/18363
1159
+ getGlobalsForEcmaVersion(languageOptions.ecmaVersion),
1160
+ languageOptions.sourceType === "commonjs"
1161
+ ? globals.commonjs
1162
+ : void 0,
1163
+ languageOptions.globals,
1164
+ );
1165
+ const varsCache = this[caches].get("vars");
1166
+
1167
+ varsCache.set("configGlobals", configGlobals);
1168
+ }
1169
+
1170
+ /**
1171
+ * Applies configuration found inside of the source code. This method is only
1172
+ * called when ESLint is running with inline configuration allowed.
1173
+ * @returns {{problems:Array<Problem>,configs:{config:FlatConfigArray,loc:Location}}} Information
1174
+ * that ESLint needs to further process the inline configuration.
1175
+ */
1176
+ applyInlineConfig() {
1177
+ const problems = [];
1178
+ const configs = [];
1179
+ const exportedVariables = {};
1180
+ const inlineGlobals = Object.create(null);
1181
+
1182
+ this.getInlineConfigNodes().forEach(comment => {
1183
+ const { label, value } = commentParser.parseDirective(
1184
+ comment.value,
1185
+ );
1186
+
1187
+ switch (label) {
1188
+ case "exported":
1189
+ Object.assign(
1190
+ exportedVariables,
1191
+ commentParser.parseListConfig(value),
1192
+ );
1193
+ break;
1194
+
1195
+ case "globals":
1196
+ case "global":
1197
+ for (const [id, idSetting] of Object.entries(
1198
+ commentParser.parseStringConfig(value),
1199
+ )) {
1200
+ let normalizedValue;
1201
+
1202
+ try {
1203
+ normalizedValue = normalizeConfigGlobal(idSetting);
1204
+ } catch (err) {
1205
+ problems.push({
1206
+ ruleId: null,
1207
+ loc: comment.loc,
1208
+ message: err.message,
1209
+ });
1210
+ continue;
1211
+ }
1212
+
1213
+ if (inlineGlobals[id]) {
1214
+ inlineGlobals[id].comments.push(comment);
1215
+ inlineGlobals[id].value = normalizedValue;
1216
+ } else {
1217
+ inlineGlobals[id] = {
1218
+ comments: [comment],
1219
+ value: normalizedValue,
1220
+ };
1221
+ }
1222
+ }
1223
+ break;
1224
+
1225
+ case "eslint": {
1226
+ const parseResult =
1227
+ commentParser.parseJSONLikeConfig(value);
1228
+
1229
+ if (parseResult.ok) {
1230
+ configs.push({
1231
+ config: {
1232
+ rules: parseResult.config,
1233
+ },
1234
+ loc: comment.loc,
1235
+ });
1236
+ } else {
1237
+ problems.push({
1238
+ ruleId: null,
1239
+ loc: comment.loc,
1240
+ message: parseResult.error.message,
1241
+ });
1242
+ }
1243
+
1244
+ break;
1245
+ }
1246
+
1247
+ // no default
1248
+ }
1249
+ });
1250
+
1251
+ // save all the new variables for later
1252
+ const varsCache = this[caches].get("vars");
1253
+
1254
+ varsCache.set("inlineGlobals", inlineGlobals);
1255
+ varsCache.set("exportedVariables", exportedVariables);
1256
+
1257
+ return {
1258
+ configs,
1259
+ problems,
1260
+ };
1261
+ }
1262
+
1263
+ /**
1264
+ * Called by ESLint core to indicate that it has finished providing
1265
+ * information. We now add in all the missing variables and ensure that
1266
+ * state-changing methods cannot be called by rules.
1267
+ * @returns {void}
1268
+ */
1269
+ finalize() {
1270
+ const varsCache = this[caches].get("vars");
1271
+ const configGlobals = varsCache.get("configGlobals");
1272
+ const inlineGlobals = varsCache.get("inlineGlobals");
1273
+ const exportedVariables = varsCache.get("exportedVariables");
1274
+ const globalScope = this.scopeManager.scopes[0];
1275
+
1276
+ addDeclaredGlobals(globalScope, configGlobals, inlineGlobals);
1277
+
1278
+ if (exportedVariables) {
1279
+ markExportedVariables(globalScope, exportedVariables);
1280
+ }
1281
+ }
1282
+
1283
+ /**
1284
+ * Traverse the source code and return the steps that were taken.
1285
+ * @returns {Array<TraversalStep>} The steps that were taken while traversing the source code.
1286
+ */
1287
+ traverse() {
1288
+ // Because the AST doesn't mutate, we can cache the steps
1289
+ if (this.#steps) {
1290
+ return this.#steps;
1291
+ }
1292
+
1293
+ const steps = (this.#steps = []);
1294
+
1295
+ /*
1296
+ * This logic works for any AST, not just ESTree. Because ESLint has allowed
1297
+ * custom parsers to return any AST, we need to ensure that the traversal
1298
+ * logic works for any AST.
1299
+ */
1300
+ let analyzer = {
1301
+ enterNode(node) {
1302
+ steps.push(
1303
+ new VisitNodeStep({
1304
+ target: node,
1305
+ phase: 1,
1306
+ args: [node],
1307
+ }),
1308
+ );
1309
+ },
1310
+ leaveNode(node) {
1311
+ steps.push(
1312
+ new VisitNodeStep({
1313
+ target: node,
1314
+ phase: 2,
1315
+ args: [node],
1316
+ }),
1317
+ );
1318
+ },
1319
+ emit(eventName, args) {
1320
+ steps.push(
1321
+ new CallMethodStep({
1322
+ target: eventName,
1323
+ args,
1324
+ }),
1325
+ );
1326
+ },
1327
+ };
1328
+
1329
+ /*
1330
+ * We do code path analysis for ESTree only. Code path analysis is not
1331
+ * necessary for other ASTs, and it's also not possible to do for other
1332
+ * ASTs because the necessary information is not available.
1333
+ *
1334
+ * Generally speaking, we can tell that the AST is an ESTree if it has a
1335
+ * Program node at the top level. This is not a perfect heuristic, but it
1336
+ * is good enough for now.
1337
+ */
1338
+ if (this.isESTree) {
1339
+ analyzer = new CodePathAnalyzer(analyzer);
1340
+ }
1341
+
1342
+ /*
1343
+ * The actual AST traversal is done by the `Traverser` class. This class
1344
+ * is responsible for walking the AST and calling the appropriate methods
1345
+ * on the `analyzer` object, which is appropriate for the given AST.
1346
+ */
1347
+ Traverser.traverse(this.ast, {
1348
+ enter(node, parent) {
1349
+ // save the parent node on a property for backwards compatibility
1350
+ node.parent = parent;
1351
+
1352
+ analyzer.enterNode(node);
1353
+ },
1354
+ leave(node) {
1355
+ analyzer.leaveNode(node);
1356
+ },
1357
+ visitorKeys: this.visitorKeys,
1358
+ });
1359
+
1360
+ return steps;
1361
+ }
1362
+ }
1363
+
1364
+ module.exports = SourceCode;