• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/**
2 * @fileoverview Require or disallow Unicode BOM
3 * @author Andrew Johnston <https://github.com/ehjay>
4 */
5"use strict";
6
7//------------------------------------------------------------------------------
8// Rule Definition
9//------------------------------------------------------------------------------
10
11module.exports = {
12    meta: {
13        type: "layout",
14
15        docs: {
16            description: "require or disallow Unicode byte order mark (BOM)",
17            category: "Stylistic Issues",
18            recommended: false,
19            url: "https://eslint.org/docs/rules/unicode-bom"
20        },
21
22        fixable: "whitespace",
23
24        schema: [
25            {
26                enum: ["always", "never"]
27            }
28        ],
29        messages: {
30            expected: "Expected Unicode BOM (Byte Order Mark).",
31            unexpected: "Unexpected Unicode BOM (Byte Order Mark)."
32        }
33    },
34
35    create(context) {
36
37        //--------------------------------------------------------------------------
38        // Public
39        //--------------------------------------------------------------------------
40
41        return {
42
43            Program: function checkUnicodeBOM(node) {
44
45                const sourceCode = context.getSourceCode(),
46                    location = { column: 0, line: 1 },
47                    requireBOM = context.options[0] || "never";
48
49                if (!sourceCode.hasBOM && (requireBOM === "always")) {
50                    context.report({
51                        node,
52                        loc: location,
53                        messageId: "expected",
54                        fix(fixer) {
55                            return fixer.insertTextBeforeRange([0, 1], "\uFEFF");
56                        }
57                    });
58                } else if (sourceCode.hasBOM && (requireBOM === "never")) {
59                    context.report({
60                        node,
61                        loc: location,
62                        messageId: "unexpected",
63                        fix(fixer) {
64                            return fixer.removeRange([-1, 0]);
65                        }
66                    });
67                }
68            }
69
70        };
71
72    }
73};
74