unbound-method.js 10.9 KB
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const experimental_utils_1 = require("@typescript-eslint/experimental-utils");
const tsutils = __importStar(require("tsutils"));
const ts = __importStar(require("typescript"));
const util = __importStar(require("../util"));
/**
 * The following is a list of exceptions to the rule
 * Generated via the following script.
 * This is statically defined to save making purposely invalid calls every lint run
 * ```
SUPPORTED_GLOBALS.flatMap(namespace => {
  const object = window[namespace];
    return Object.getOwnPropertyNames(object)
      .filter(
        name =>
          !name.startsWith('_') &&
          typeof object[name] === 'function',
      )
      .map(name => {
        try {
          const x = object[name];
          x();
        } catch (e) {
          if (e.message.includes("called on non-object")) {
            return `${namespace}.${name}`;
          }
        }
      });
}).filter(Boolean);
   * ```
 */
const nativelyNotBoundMembers = new Set([
    'Promise.all',
    'Promise.race',
    'Promise.resolve',
    'Promise.reject',
    'Promise.allSettled',
    'Object.defineProperties',
    'Object.defineProperty',
    'Reflect.defineProperty',
    'Reflect.deleteProperty',
    'Reflect.get',
    'Reflect.getOwnPropertyDescriptor',
    'Reflect.getPrototypeOf',
    'Reflect.has',
    'Reflect.isExtensible',
    'Reflect.ownKeys',
    'Reflect.preventExtensions',
    'Reflect.set',
    'Reflect.setPrototypeOf',
]);
const SUPPORTED_GLOBALS = [
    'Number',
    'Object',
    'String',
    'RegExp',
    'Symbol',
    'Array',
    'Proxy',
    'Date',
    'Infinity',
    'Atomics',
    'Reflect',
    'console',
    'Math',
    'JSON',
    'Intl',
];
const nativelyBoundMembers = SUPPORTED_GLOBALS.map(namespace => {
    if (!(namespace in global)) {
        // node.js might not have namespaces like Intl depending on compilation options
        // https://nodejs.org/api/intl.html#intl_options_for_building_node_js
        return [];
    }
    const object = global[namespace];
    return Object.getOwnPropertyNames(object)
        .filter(name => !name.startsWith('_') &&
        typeof object[name] === 'function')
        .map(name => `${namespace}.${name}`);
})
    .reduce((arr, names) => arr.concat(names), [])
    .filter(name => !nativelyNotBoundMembers.has(name));
const isNotImported = (symbol, currentSourceFile) => {
    const { valueDeclaration } = symbol;
    if (!valueDeclaration) {
        // working around https://github.com/microsoft/TypeScript/issues/31294
        return false;
    }
    return (!!currentSourceFile &&
        currentSourceFile !== valueDeclaration.getSourceFile());
};
const getNodeName = (node) => node.type === experimental_utils_1.AST_NODE_TYPES.Identifier ? node.name : null;
const getMemberFullName = (node) => `${getNodeName(node.object)}.${getNodeName(node.property)}`;
exports.default = util.createRule({
    name: 'unbound-method',
    meta: {
        docs: {
            category: 'Best Practices',
            description: 'Enforces unbound methods are called with their expected scope',
            recommended: 'error',
            requiresTypeChecking: true,
        },
        messages: {
            unbound: 'Avoid referencing unbound methods which may cause unintentional scoping of `this`.',
        },
        schema: [
            {
                type: 'object',
                properties: {
                    ignoreStatic: {
                        type: 'boolean',
                    },
                },
                additionalProperties: false,
            },
        ],
        type: 'problem',
    },
    defaultOptions: [
        {
            ignoreStatic: false,
        },
    ],
    create(context, [{ ignoreStatic }]) {
        const parserServices = util.getParserServices(context);
        const checker = parserServices.program.getTypeChecker();
        const currentSourceFile = parserServices.program.getSourceFile(context.getFilename());
        return {
            MemberExpression(node) {
                if (isSafeUse(node)) {
                    return;
                }
                const objectSymbol = checker.getSymbolAtLocation(parserServices.esTreeNodeToTSNodeMap.get(node.object));
                if (objectSymbol &&
                    nativelyBoundMembers.includes(getMemberFullName(node)) &&
                    isNotImported(objectSymbol, currentSourceFile)) {
                    return;
                }
                const originalNode = parserServices.esTreeNodeToTSNodeMap.get(node);
                const symbol = checker.getSymbolAtLocation(originalNode);
                if (symbol && isDangerousMethod(symbol, ignoreStatic)) {
                    context.report({
                        messageId: 'unbound',
                        node,
                    });
                }
            },
            'VariableDeclarator, AssignmentExpression'(node) {
                const [idNode, initNode] = node.type === experimental_utils_1.AST_NODE_TYPES.VariableDeclarator
                    ? [node.id, node.init]
                    : [node.left, node.right];
                if (initNode && idNode.type === experimental_utils_1.AST_NODE_TYPES.ObjectPattern) {
                    const tsNode = parserServices.esTreeNodeToTSNodeMap.get(initNode);
                    const rightSymbol = checker.getSymbolAtLocation(tsNode);
                    const initTypes = checker.getTypeAtLocation(tsNode);
                    const notImported = rightSymbol && isNotImported(rightSymbol, currentSourceFile);
                    idNode.properties.forEach(property => {
                        if (property.type === experimental_utils_1.AST_NODE_TYPES.Property &&
                            property.key.type === experimental_utils_1.AST_NODE_TYPES.Identifier) {
                            if (notImported &&
                                util.isIdentifier(initNode) &&
                                nativelyBoundMembers.includes(`${initNode.name}.${property.key.name}`)) {
                                return;
                            }
                            const symbol = initTypes.getProperty(property.key.name);
                            if (symbol && isDangerousMethod(symbol, ignoreStatic)) {
                                context.report({
                                    messageId: 'unbound',
                                    node,
                                });
                            }
                        }
                    });
                }
            },
        };
    },
});
function isDangerousMethod(symbol, ignoreStatic) {
    var _a, _b;
    const { valueDeclaration } = symbol;
    if (!valueDeclaration) {
        // working around https://github.com/microsoft/TypeScript/issues/31294
        return false;
    }
    switch (valueDeclaration.kind) {
        case ts.SyntaxKind.PropertyDeclaration:
            return (((_a = valueDeclaration.initializer) === null || _a === void 0 ? void 0 : _a.kind) ===
                ts.SyntaxKind.FunctionExpression);
        case ts.SyntaxKind.MethodDeclaration:
        case ts.SyntaxKind.MethodSignature: {
            const decl = valueDeclaration;
            const firstParam = decl.parameters[0];
            const thisArgIsVoid = (firstParam === null || firstParam === void 0 ? void 0 : firstParam.name.kind) === ts.SyntaxKind.Identifier &&
                (firstParam === null || firstParam === void 0 ? void 0 : firstParam.name.escapedText) === 'this' &&
                ((_b = firstParam === null || firstParam === void 0 ? void 0 : firstParam.type) === null || _b === void 0 ? void 0 : _b.kind) === ts.SyntaxKind.VoidKeyword;
            return (!thisArgIsVoid &&
                !(ignoreStatic &&
                    tsutils.hasModifier(valueDeclaration.modifiers, ts.SyntaxKind.StaticKeyword)));
        }
    }
    return false;
}
function isSafeUse(node) {
    const parent = node.parent;
    switch (parent === null || parent === void 0 ? void 0 : parent.type) {
        case experimental_utils_1.AST_NODE_TYPES.IfStatement:
        case experimental_utils_1.AST_NODE_TYPES.ForStatement:
        case experimental_utils_1.AST_NODE_TYPES.MemberExpression:
        case experimental_utils_1.AST_NODE_TYPES.SwitchStatement:
        case experimental_utils_1.AST_NODE_TYPES.UpdateExpression:
        case experimental_utils_1.AST_NODE_TYPES.WhileStatement:
            return true;
        case experimental_utils_1.AST_NODE_TYPES.CallExpression:
            return parent.callee === node;
        case experimental_utils_1.AST_NODE_TYPES.ConditionalExpression:
            return parent.test === node;
        case experimental_utils_1.AST_NODE_TYPES.TaggedTemplateExpression:
            return parent.tag === node;
        case experimental_utils_1.AST_NODE_TYPES.UnaryExpression:
            // the first case is safe for obvious
            // reasons. The second one is also fine
            // since we're returning something falsy
            return ['typeof', '!', 'void', 'delete'].includes(parent.operator);
        case experimental_utils_1.AST_NODE_TYPES.BinaryExpression:
            return ['instanceof', '==', '!=', '===', '!=='].includes(parent.operator);
        case experimental_utils_1.AST_NODE_TYPES.AssignmentExpression:
            return parent.operator === '=' && node === parent.left;
        case experimental_utils_1.AST_NODE_TYPES.ChainExpression:
        case experimental_utils_1.AST_NODE_TYPES.TSNonNullExpression:
        case experimental_utils_1.AST_NODE_TYPES.TSAsExpression:
        case experimental_utils_1.AST_NODE_TYPES.TSTypeAssertion:
            return isSafeUse(parent);
        case experimental_utils_1.AST_NODE_TYPES.LogicalExpression:
            if (parent.operator === '&&' && parent.left === node) {
                // this is safe, as && will return the left if and only if it's falsy
                return true;
            }
            // in all other cases, it's likely the logical expression will return the method ref
            // so make sure the parent is a safe usage
            return isSafeUse(parent);
    }
    return false;
}
//# sourceMappingURL=unbound-method.js.map