no-deprecated-api.js 18.3 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
/**
 * @fileoverview Rule to disallow deprecated API.
 * @author Toru Nagashima
 * @copyright 2016 Toru Nagashima. All rights reserved.
 * See LICENSE file in root directory for full license.
 */
"use strict"

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

const deprecatedApis = require("../util/deprecated-apis")
const getValueIfString = require("../util/get-value-if-string")

//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------

const SENTINEL_TYPE = /^(?:.+?Statement|.+?Declaration|(?:Array|ArrowFunction|Assignment|Call|Class|Function|Member|New|Object)Expression|AssignmentPattern|Program|VariableDeclarator)$/
const MODULE_ITEMS = getDeprecatedItems(deprecatedApis.modules, [], [])
const GLOBAL_ITEMS = getDeprecatedItems(deprecatedApis.globals, [], [])

/**
 * Gets the array of deprecated items.
 *
 * It's the paths which are separated by dots.
 * E.g. `buffer.Buffer`, `events.EventEmitter.listenerCount`
 *
 * @param {object} definition - The definition of deprecated APIs.
 * @param {string[]} result - The array of the result.
 * @param {string[]} stack - The array to manage the stack of paths.
 * @returns {string[]} `result`.
 */
function getDeprecatedItems(definition, result, stack) {
    for (const key of Object.keys(definition)) {
        const item = definition[key]

        if (key === "$call") {
            result.push(`${stack.join(".")}()`)
        }
        else if (key === "$constructor") {
            result.push(`new ${stack.join(".")}()`)
        }
        else {
            stack.push(key)

            if (item.$deprecated) {
                result.push(stack.join("."))
            }
            else {
                getDeprecatedItems(item, result, stack)
            }

            stack.pop()
        }
    }

    return result
}

/**
 * Converts from a version number to a version text to display.
 *
 * @param {number} value - A version number to convert.
 * @returns {string} Covnerted text.
 */
function toVersionText(value) {
    if (value <= 0.12) {
        return value.toFixed(2)
    }
    if (value < 1) {
        return value.toFixed(1)
    }
    return String(value)
}

/**
 * Makes a replacement message.
 *
 * @param {string|null} replacedBy - The text of substitute way.
 * @returns {string} Replacement message.
 */
function toReplaceMessage(replacedBy) {
    return replacedBy ? ` Use ${replacedBy} instead.` : ""
}

/**
 * Gets the property name from a MemberExpression node or a Property node.
 *
 * @param {ASTNode} node - A node to get.
 * @returns {string|null} The property name of the node.
 */
function getPropertyName(node) {
    switch (node.type) {
        case "MemberExpression":
            if (node.computed) {
                return getValueIfString(node.property)
            }
            return node.property.name

        case "Property":
            if (node.computed) {
                return getValueIfString(node.key)
            }
            if (node.key.type === "Literal") {
                return String(node.key.value)
            }
            return node.key.name

        // no default
    }

    /* istanbul ignore next: unreachable */
    return null
}

/**
 * Checks a given node is a ImportDeclaration node.
 *
 * @param {ASTNode} node - A node to check.
 * @returns {boolean} `true` if the node is a ImportDeclaration node.
 */
function isImportDeclaration(node) {
    return node.type === "ImportDeclaration"
}

/**
 * Finds the variable object of a given Identifier node.
 *
 * @param {ASTNode} node - An Identifier node to find.
 * @param {escope.Scope} initialScope - A scope to start searching.
 * @returns {escope.Variable} Found variable object.
 */
function findVariable(node, initialScope) {
    const location = node.range[0]
    let variable = null

    // Dive into the scope that the node exists.
    for (const childScope of initialScope.childScopes) {
        const range = childScope.block.range

        if (range[0] <= location && location < range[1]) {
            variable = findVariable(node, childScope)
            if (variable != null) {
                return variable
            }
        }
    }

    // Find the variable of that name in this scope or ancestor scopes.
    let scope = initialScope
    while (scope != null) {
        variable = scope.set.get(node.name)
        if (variable != null) {
            return variable
        }

        scope = scope.upper
    }

    return null
}

/**
 * Gets the top member expression node.
 *
 * @param {ASTNode} identifier - The node to get.
 * @returns {ASTNode} The top member expression node.
 */
function getTopMemberExpression(identifier) {
    if (identifier.type !== "Identifier" && identifier.type !== "Literal") {
        return identifier
    }

    let node = identifier
    while (node.parent.type === "MemberExpression") {
        node = node.parent
    }

    return node
}

/**
 * The definition of this rule.
 *
 * @param {RuleContext} context - The rule context to check.
 * @returns {object} The definition of this rule.
 */
function create(context) {
    const options = context.options[0] || {}
    const ignoredModuleItems = options.ignoreModuleItems || []
    const ignoredGlobalItems = options.ignoreGlobalItems || []
    let globalScope = null
    const varStack = []

    /**
     * Reports a use of a deprecated API.
     *
     * @param {ASTNode} node - A node to report.
     * @param {string} name - The name of a deprecated API.
     * @param {{since: number, replacedBy: string}} info - Information of the API.
     * @returns {void}
     */
    function report(node, name, info) {
        context.report({
            node,
            loc: getTopMemberExpression(node).loc,
            message: "{{name}} was deprecated since v{{version}}.{{replace}}",
            data: {
                name,
                version: toVersionText(info.since),
                replace: toReplaceMessage(info.replacedBy),
            },
        })
    }

    /**
     * Reports a use of a deprecated module.
     *
     * @param {ASTNode} node - A node to report.
     * @param {string} name - The name of a deprecated module.
     * @param {{since: number, replacedBy: string, global: boolean}} info - Information of the module.
     * @returns {void}
     */
    function reportModule(node, name, info) {
        if (ignoredModuleItems.indexOf(name) === -1) {
            report(node, `'${name}' module`, info)
        }
    }

    /**
     * Reports a use of a deprecated property.
     *
     * @param {ASTNode} node - A node to report.
     * @param {string[]} path - The path to a deprecated property.
     * @param {{since: number, replacedBy: string, global: boolean}} info - Information of the property.
     * @returns {void}
     */
    function reportCall(node, path, info) {
        const ignored = info.global ? ignoredGlobalItems : ignoredModuleItems
        const name = `${path.join(".")}()`

        if (ignored.indexOf(name) === -1) {
            report(node, `'${name}'`, info)
        }
    }

    /**
     * Reports a use of a deprecated property.
     *
     * @param {ASTNode} node - A node to report.
     * @param {string[]} path - The path to a deprecated property.
     * @param {{since: number, replacedBy: string, global: boolean}} info - Information of the property.
     * @returns {void}
     */
    function reportConstructor(node, path, info) {
        const ignored = info.global ? ignoredGlobalItems : ignoredModuleItems
        const name = `new ${path.join(".")}()`

        if (ignored.indexOf(name) === -1) {
            report(node, `'${name}'`, info)
        }
    }

    /**
     * Reports a use of a deprecated property.
     *
     * @param {ASTNode} node - A node to report.
     * @param {string[]} path - The path to a deprecated property.
     * @param {string} key - The name of the property.
     * @param {{since: number, replacedBy: string, global: boolean}} info - Information of the property.
     * @returns {void}
     */
    function reportProperty(node, path, key, info) {
        const ignored = info.global ? ignoredGlobalItems : ignoredModuleItems

        path.push(key)
        const name = path.join(".")
        path.pop()

        if (ignored.indexOf(name) === -1) {
            report(node, `'${name}'`, info)
        }
    }

    /**
     * Checks violations in destructuring assignments.
     *
     * @param {ASTNode} node - A pattern node to check.
     * @param {string[]} path - The path to a deprecated property.
     * @param {object} infoMap - A map of properties' information.
     * @returns {void}
     */
    function checkDestructuring(node, path, infoMap) {
        switch (node.type) {
            case "AssignmentPattern":
                checkDestructuring(node.left, path, infoMap)
                break

            case "Identifier": {
                const variable = findVariable(node, globalScope)
                if (variable != null) {
                    checkVariable(variable, path, infoMap)
                }
                break
            }
            case "ObjectPattern":
                for (const property of node.properties) {
                    const key = getPropertyName(property)
                    if (key != null && hasOwnProperty.call(infoMap, key)) {
                        const keyInfo = infoMap[key]
                        if (keyInfo.$deprecated) {
                            reportProperty(property.key, path, key, keyInfo)
                        }
                        else {
                            path.push(key)
                            checkDestructuring(property.value, path, keyInfo)
                            path.pop()
                        }
                    }
                }
                break

            // no default
        }
    }

    /**
     * Checks violations in properties.
     *
     * @param {ASTNode} root - A node to check.
     * @param {string[]} path - The path to a deprecated property.
     * @param {object} infoMap - A map of properties' information.
     * @returns {void}
     */
    function checkProperties(root, path, infoMap) { //eslint-disable-line complexity
        let node = root
        while (!SENTINEL_TYPE.test(node.parent.type)) {
            node = node.parent
        }

        const parent = node.parent
        switch (parent.type) {
            case "CallExpression":
                if (parent.callee === node && infoMap.$call != null) {
                    reportCall(parent, path, infoMap.$call)
                }
                break

            case "NewExpression":
                if (parent.callee === node && infoMap.$constructor != null) {
                    reportConstructor(parent, path, infoMap.$constructor)
                }
                break

            case "MemberExpression":
                if (parent.object === node) {
                    const key = getPropertyName(parent)
                    if (key != null && hasOwnProperty.call(infoMap, key)) {
                        const keyInfo = infoMap[key]
                        if (keyInfo.$deprecated) {
                            reportProperty(parent.property, path, key, keyInfo)
                        }
                        else {
                            path.push(key)
                            checkProperties(parent, path, keyInfo)
                            path.pop()
                        }
                    }
                }
                break

            case "AssignmentExpression":
                if (parent.right === node) {
                    checkDestructuring(parent.left, path, infoMap)
                    checkProperties(parent, path, infoMap)
                }
                break

            case "AssignmentPattern":
                if (parent.right === node) {
                    checkDestructuring(parent.left, path, infoMap)
                }
                break

            case "VariableDeclarator":
                if (parent.init === node) {
                    checkDestructuring(parent.id, path, infoMap)
                }
                break

            // no default
        }
    }

    /**
     * Checks violations in the references of a given variable.
     *
     * @param {escope.Variable} variable - A variable to check.
     * @param {string[]} path - The path to a deprecated property.
     * @param {object} infoMap - A map of properties' information.
     * @returns {void}
     */
    function checkVariable(variable, path, infoMap) {
        if (varStack.indexOf(variable) !== -1) {
            return
        }
        varStack.push(variable)

        if (infoMap.$deprecated) {
            const key = path.pop()
            for (const reference of variable.references.filter(r => r.isRead())) {
                reportProperty(reference.identifier, path, key, infoMap)
            }
        }
        else {
            for (const reference of variable.references.filter(r => r.isRead())) {
                checkProperties(reference.identifier, path, infoMap)
            }
        }

        varStack.pop()
    }

    /**
     * Checks violations in a ModuleSpecifier node.
     *
     * @param {ASTNode} node - A ModuleSpecifier node to check.
     * @param {string[]} path - The path to a deprecated property.
     * @param {object} infoMap - A map of properties' information.
     * @returns {void}
     */
    function checkImportSpecifier(node, path, infoMap) {
        switch (node.type) {
            case "ImportSpecifier": {
                const key = node.imported.name
                if (hasOwnProperty.call(infoMap, key)) {
                    const keyInfo = infoMap[key]
                    if (keyInfo.$deprecated) {
                        reportProperty(node.imported, path, key, keyInfo)
                    }
                    else {
                        path.push(key)
                        checkVariable(
                            findVariable(node.local, globalScope),
                            path,
                            keyInfo
                        )
                        path.pop()
                    }
                }
                break
            }
            case "ImportDefaultSpecifier":
                checkVariable(
                    findVariable(node.local, globalScope),
                    path,
                    infoMap
                )
                break

            case "ImportNamespaceSpecifier":
                checkVariable(
                    findVariable(node.local, globalScope),
                    path,
                    Object.assign({}, infoMap, {default: infoMap})
                )
                break

            // no default
        }
    }

    /**
     * Checks violations for CommonJS modules.
     * @returns {void}
     */
    function checkCommonJsModules() {
        const infoMap = deprecatedApis.modules
        const variable = globalScope.set.get("require")

        if (variable == null || variable.defs.length !== 0) {
            return
        }

        for (const reference of variable.references.filter(r => r.isRead())) {
            const id = reference.identifier
            const node = id.parent

            if (node.type === "CallExpression" && node.callee === id) {
                const key = getValueIfString(node.arguments[0])
                if (key != null && hasOwnProperty.call(infoMap, key)) {
                    const moduleInfo = infoMap[key]
                    if (moduleInfo.$deprecated) {
                        reportModule(node, key, moduleInfo)
                    }
                    else {
                        checkProperties(node, [key], moduleInfo)
                    }
                }
            }
        }
    }

    /**
     * Checks violations for ES2015 modules.
     * @param {ASTNode} programNode - A program node to check.
     * @returns {void}
     */
    function checkES2015Modules(programNode) {
        const infoMap = deprecatedApis.modules

        for (const node of programNode.body.filter(isImportDeclaration)) {
            const key = node.source.value
            if (hasOwnProperty.call(infoMap, key)) {
                const moduleInfo = infoMap[key]
                if (moduleInfo.$deprecated) {
                    reportModule(node, key, moduleInfo)
                }
                else {
                    for (const specifier of node.specifiers) {
                        checkImportSpecifier(specifier, [key], moduleInfo)
                    }
                }
            }
        }
    }

    /**
     * Checks violations for global variables.
     * @returns {void}
     */
    function checkGlobals() {
        const infoMap = deprecatedApis.globals

        for (const key of Object.keys(infoMap)) {
            const keyInfo = infoMap[key]
            const variable = globalScope.set.get(key)

            if (variable != null && variable.defs.length === 0) {
                checkVariable(variable, [key], keyInfo)
            }
        }
    }

    return {
        "Program:exit"(node) {
            globalScope = context.getScope()

            checkCommonJsModules()
            checkES2015Modules(node)
            checkGlobals()
        },
    }
}

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

module.exports = {
    create,
    meta: {
        docs: {
            description: "disallow deprecated APIs",
            category: "Best Practices",
            recommended: true,
        },
        fixable: false,
        schema: [
            {
                type: "object",
                properties: {
                    ignoreModuleItems: {
                        type: "array",
                        items: {enum: MODULE_ITEMS},
                        additionalItems: false,
                        uniqueItems: true,
                    },
                    ignoreGlobalItems: {
                        type: "array",
                        items: {enum: GLOBAL_ITEMS},
                        additionalItems: false,
                        uniqueItems: true,
                    },

                    // Deprecated since v4.2.0
                    ignoreIndirectDependencies: {type: "boolean"},
                },
                additionalProperties: false,
            },
        ],
    },
}