no-new-buffer.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. 'use strict';
  2. const {getStaticValue} = require('eslint-utils');
  3. const {newExpressionSelector} = require('./selectors/index.js');
  4. const {switchNewExpressionToCallExpression} = require('./fix/index.js');
  5. const ERROR = 'error';
  6. const ERROR_UNKNOWN = 'error-unknown';
  7. const SUGGESTION = 'suggestion';
  8. const messages = {
  9. [ERROR]: '`new Buffer()` is deprecated, use `Buffer.{{method}}()` instead.',
  10. [ERROR_UNKNOWN]: '`new Buffer()` is deprecated, use `Buffer.alloc()` or `Buffer.from()` instead.',
  11. [SUGGESTION]: 'Switch to `Buffer.{{method}}()`.',
  12. };
  13. const inferMethod = (bufferArguments, scope) => {
  14. if (bufferArguments.length !== 1) {
  15. return 'from';
  16. }
  17. const [firstArgument] = bufferArguments;
  18. if (firstArgument.type === 'SpreadElement') {
  19. return;
  20. }
  21. if (firstArgument.type === 'ArrayExpression' || firstArgument.type === 'TemplateLiteral') {
  22. return 'from';
  23. }
  24. const staticResult = getStaticValue(firstArgument, scope);
  25. if (staticResult) {
  26. const {value} = staticResult;
  27. if (typeof value === 'number') {
  28. return 'alloc';
  29. }
  30. if (
  31. typeof value === 'string'
  32. || Array.isArray(value)
  33. ) {
  34. return 'from';
  35. }
  36. }
  37. };
  38. function fix(node, sourceCode, method) {
  39. return function * (fixer) {
  40. yield fixer.insertTextAfter(node.callee, `.${method}`);
  41. yield * switchNewExpressionToCallExpression(node, sourceCode, fixer);
  42. };
  43. }
  44. /** @param {import('eslint').Rule.RuleContext} context */
  45. const create = context => {
  46. const sourceCode = context.getSourceCode();
  47. return {
  48. [newExpressionSelector('Buffer')]: node => {
  49. const method = inferMethod(node.arguments, context.getScope());
  50. if (method) {
  51. return {
  52. node,
  53. messageId: ERROR,
  54. data: {method},
  55. fix: fix(node, sourceCode, method),
  56. };
  57. }
  58. return {
  59. node,
  60. messageId: ERROR_UNKNOWN,
  61. suggest: ['from', 'alloc'].map(method => ({
  62. messageId: SUGGESTION,
  63. data: {method},
  64. fix: fix(node, sourceCode, method),
  65. })),
  66. };
  67. },
  68. };
  69. };
  70. /** @type {import('eslint').Rule.RuleModule} */
  71. module.exports = {
  72. create,
  73. meta: {
  74. type: 'problem',
  75. docs: {
  76. description: 'Enforce the use of `Buffer.from()` and `Buffer.alloc()` instead of the deprecated `new Buffer()`.',
  77. },
  78. fixable: 'code',
  79. hasSuggestions: true,
  80. messages,
  81. },
  82. };