|
| 1 | +/** |
| 2 | + * @author tyankatsu |
| 3 | + * @copyright 2020 tyankatsu. All rights reserved. |
| 4 | + * See LICENSE file in root directory for full license. |
| 5 | + */ |
| 6 | +import { AST } from "vue-eslint-parser"; |
| 7 | +import minimatch from "minimatch"; |
| 8 | +import { createRule, Env } from "../utils"; |
| 9 | +import * as Fs from "fs"; |
| 10 | + |
| 11 | +const PREFIX = "GRIDSOME_"; |
| 12 | + |
| 13 | +type Options = { |
| 14 | + pathsForBrowserfile?: string[]; |
| 15 | + envPath?: string; |
| 16 | +}; |
| 17 | + |
| 18 | +const defaultOptions: [Options] = [{}]; |
| 19 | + |
| 20 | +type MessageIds = "useEnvPrefix"; |
| 21 | +export = createRule<[Options], MessageIds>({ |
| 22 | + name: "use-env-prefix", |
| 23 | + meta: { |
| 24 | + docs: { |
| 25 | + description: "Use prefix `GRIDSOME_` when using process.env in browser", |
| 26 | + category: "Possible Errors", |
| 27 | + recommended: false, |
| 28 | + }, |
| 29 | + type: "problem", |
| 30 | + messages: { |
| 31 | + useEnvPrefix: "Use `process.env.{{ addedPrefixEnv }}`.", |
| 32 | + }, |
| 33 | + schema: [ |
| 34 | + { |
| 35 | + type: "object", |
| 36 | + properties: { |
| 37 | + pathsForBrowserfile: { |
| 38 | + type: "array", |
| 39 | + items: { |
| 40 | + type: "string", |
| 41 | + }, |
| 42 | + }, |
| 43 | + envPath: { |
| 44 | + type: "string", |
| 45 | + }, |
| 46 | + }, |
| 47 | + }, |
| 48 | + ], |
| 49 | + }, |
| 50 | + defaultOptions, |
| 51 | + create(context) { |
| 52 | + const filename = context.getFilename(); |
| 53 | + |
| 54 | + const pathsForBrowserfileOption = context.options[0] |
| 55 | + ?.pathsForBrowserfile || ["src/**/*"]; |
| 56 | + const envPathOption = context.options[0]?.envPath || ".env"; |
| 57 | + |
| 58 | + const isClientfile = pathsForBrowserfileOption.some((clientPath) => |
| 59 | + minimatch(filename, clientPath) |
| 60 | + ); |
| 61 | + |
| 62 | + const envSource = Fs.readFileSync(envPathOption, { encoding: "utf8" }); |
| 63 | + const parsedEnvSource = new Env(envSource).parse(); |
| 64 | + |
| 65 | + return { |
| 66 | + "MemberExpression[object.object.name='process'][object.property.name='env']"( |
| 67 | + node: AST.ESLintMemberExpression |
| 68 | + ) { |
| 69 | + if (!isClientfile) return; |
| 70 | + if (node.property.type !== "Identifier") return; |
| 71 | + if (node.property.name.includes(PREFIX)) return; |
| 72 | + |
| 73 | + const envName = node.property.name; |
| 74 | + |
| 75 | + if (parsedEnvSource.has(envName)) { |
| 76 | + context.report({ |
| 77 | + node, |
| 78 | + loc: node.loc, |
| 79 | + messageId: "useEnvPrefix", |
| 80 | + data: { |
| 81 | + addedPrefixEnv: `${PREFIX}${envName}`, |
| 82 | + }, |
| 83 | + }); |
| 84 | + } |
| 85 | + }, |
| 86 | + }; |
| 87 | + }, |
| 88 | +}); |
0 commit comments