租房小程序前端代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2079 lines
65 KiB

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