@sap/eslint-plugin-cds 2.0.4 → 2.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,27 +1,39 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.parseForESLint = exports.parse = void 0;
7
- const utils_1 = require("./utils");
8
- const cds_1 = __importDefault(require("@sap/cds"));
9
- function parse(code, options) {
10
- return parseForESLint(code, options).ast;
11
- }
12
- exports.parse = parse;
13
- function parseForESLint(code, options) {
14
- cds_1.default.getLocation = utils_1.getLocation;
15
- cds_1.default.getRange = utils_1.getRange;
1
+ /**
2
+ * Custom ESLint parser:
3
+ * https://eslint.org/docs/developer-guide/working-with-custom-parsers
4
+ * This file must:
5
+ * - Expose 'parseForESLint' method on the parser which should return the AST,
6
+ * optional properties services, a scopeManager, and visitorKeys
7
+ * - Expose default method 'parse' which should return the AST
8
+ * Both methods should take in the source code and an optional configuration
9
+ * (parserOptions). Note, that because we use a 'empty' preprocessor, the
10
+ * parser is only used by ESLint's ruleTester.
11
+ */
12
+
13
+ const {
14
+ getAST,
15
+ getCDSProxy,
16
+ getLocation,
17
+ getRange,
18
+ } = require("../impl/utils/model");
19
+ const cds = require("@sap/cds");
20
+
21
+ module.exports = {
22
+ parse: function (code, options) {
23
+ return module.exports.parseForESLint(code, options).ast;
24
+ },
25
+
26
+ parseForESLint: function (code) {
27
+ cds.getLocation = getLocation;
28
+ cds.getRange = getRange;
16
29
  return {
17
- ast: utils_1.getAST(code),
18
- services: {
19
- cdsProxy: utils_1.getProxy(cds_1.default)
20
- },
21
- scopeManager: null,
22
- tokensAndComments: [],
23
- visitorKeys: null
30
+ ast: getAST(code),
31
+ services: {
32
+ cdsProxy: getCDSProxy(cds),
33
+ },
34
+ scopeManager: null,
35
+ tokensAndComments: [],
36
+ visitorKeys: null,
24
37
  };
25
- }
26
- exports.parseForESLint = parseForESLint;
27
- //# sourceMappingURL=parser.js.map
38
+ },
39
+ };
@@ -0,0 +1,23 @@
1
+ /**
2
+ * ESLint custom processor:
3
+ * https://eslint.org/docs/developer-guide/working-with-plugins#processors-in-plugins
4
+ * This processor is used to avoid parsing errors when this plugin is extended
5
+ * in ESLint alongside other plugins, such as prettier which then also try to
6
+ * read the new file types exposed via globs.
7
+ * Note, that because we cache the file contents and return empty files, the
8
+ * plugin's parser is not actually used and we must retrieve the file contents
9
+ * later on (ruleFactory).
10
+ */
11
+
12
+ const { Cache } = require("./utils/model");
13
+ const { isValidFile } = require("./utils/helpers");
14
+
15
+ module.exports = {
16
+ preprocess: function (text, filename) {
17
+ if (isValidFile(filename)) {
18
+ Cache.set(`processed:${filename}`, text);
19
+ }
20
+ return [{ text: "", filename }];
21
+ },
22
+ supportsAutofix: true,
23
+ };
@@ -1,117 +1,319 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.getRuleTester = exports.createRule = void 0;
7
- const path_1 = __importDefault(require("path"));
8
- const eslint_1 = require("eslint");
9
- const utils_1 = require("./utils");
10
- const constants_1 = require("./constants");
11
- function createRule(defineMeta, defineReport) {
12
- return {
13
- meta: Object.assign({}, defineMeta),
14
- create(context) {
15
- {
16
- return cbRuleFunctions(context, defineReport);
17
- }
18
- }
19
- };
20
- }
21
- exports.createRule = createRule;
22
- function cbRuleFunctions(context, defineReport) {
23
- return {
24
- Program(node) {
25
- var _a, _b, _c, _d, _e, _f;
26
- const ruleID = context.id;
27
- const sourcecode = context.getSourceCode();
28
- const code = sourcecode.getText(node);
29
- const filePath = context.getFilename();
30
- const configPath = path_1.default.dirname(utils_1.getConfigPath(filePath));
31
- const cds = context.parserServices.cdsProxy;
32
- if (!utils_1.Cache.get('configpath') || configPath !== utils_1.Cache.get('configpath')) {
33
- utils_1.Cache.set('configpath', configPath);
34
- }
35
- if ((_a = context.options[0]) === null || _a === void 0 ? void 0 : _a.environment) {
36
- utils_1.Cache.set('environment', context.options[0].environment);
37
- }
38
- if (!utils_1.Cache.has(`modelfiles:${configPath}`)) {
39
- utils_1.loadModel(code, configPath, filePath);
40
- }
41
- if (utils_1.Cache.has(`modelfiles:${configPath}`)) {
42
- const modelFiles = utils_1.Cache.get(`modelfiles:${configPath}`);
43
- if (modelFiles.includes(filePath) && code !== utils_1.Cache.get(`file:${filePath}`)) {
44
- utils_1.Cache.set(`file:${filePath}`, code);
45
- utils_1.updateModel(code, configPath, filePath);
46
- }
47
- }
48
- let report = [];
49
- if (((cds === null || cds === void 0 ? void 0 : cds.model) || (cds === null || cds === void 0 ? void 0 : cds.environment)) && !((_b = cds === null || cds === void 0 ? void 0 : cds.model) === null || _b === void 0 ? void 0 : _b.err) && !(ruleID === '@sap/cds/csn-compile-error' || ruleID === 'csn-compile-error')) {
50
- if (utils_1.Cache.has(`err:${configPath}`)) {
51
- utils_1.Cache.remove(`err:${configPath}`);
52
- }
53
- if ((cds === null || cds === void 0 ? void 0 : cds.model) || (cds === null || cds === void 0 ? void 0 : cds.environment)) {
54
- report = defineReport(cds, context, node);
55
- }
56
- if (report.length > 0) {
57
- const reportProperties = { filePath, ruleID, code, sourcecode };
58
- reportErrors(report, context, reportProperties);
59
- }
60
- }
61
- else {
62
- if ((_c = cds === null || cds === void 0 ? void 0 : cds.model) === null || _c === void 0 ? void 0 : _c.err) {
63
- if ((_f = (_e = (_d = cds === null || cds === void 0 ? void 0 : cds.model) === null || _d === void 0 ? void 0 : _d.err) === null || _e === void 0 ? void 0 : _e.message) === null || _f === void 0 ? void 0 : _f.startsWith('CDS compilation failed')) {
64
- if (ruleID === '@sap/cds/csn-compile-error' || ruleID === 'csn-compile-error') {
65
- report = defineReport(cds, context, node);
66
- if (report.length > 0) {
67
- const reportProperties = { filePath, ruleID, code, sourcecode };
68
- reportErrors(report, context, reportProperties);
69
- }
70
- }
71
- }
72
- }
73
- }
74
- }
75
- };
76
- }
77
- function reportErrors(report, context, properties) {
78
- report.forEach((entry, i) => {
79
- var _a, _b;
80
- if (entry) {
81
- const ruleID = properties.ruleID;
82
- const fileRel = entry.file;
83
- let fileAbs = entry.file || '';
84
- if (!path_1.default.isAbsolute(fileAbs)) {
85
- fileAbs = (fileRel) ? path_1.default.join(utils_1.Cache.get('configpath'), fileRel) : '';
86
- }
87
- const line = (_b = (_a = entry === null || entry === void 0 ? void 0 : entry.loc) === null || _a === void 0 ? void 0 : _a.start) === null || _b === void 0 ? void 0 : _b.line;
88
- const rulesDisabled = utils_1.getDisabledFromComments(properties.code, properties.sourcecode, line);
89
- let isDisabled = false;
90
- if (line && ruleID in rulesDisabled && rulesDisabled[ruleID] === "off") {
91
- isDisabled = true;
92
- }
93
- if (!isDisabled) {
94
- if (constants_1.Constants.envRules.includes(ruleID) || constants_1.Constants.envRules.includes(ruleID.replace('@sap/cds/', ''))) {
95
- entry.file = utils_1.Cache.get('configpath');
96
- context.report(entry);
97
- }
98
- else if ((fileRel && ((fileAbs === properties.filePath) || fileRel === '<stdin>.cds'))) {
99
- context.report(entry);
100
- }
101
- }
102
- }
103
- });
104
- }
105
- function getRuleTester(relPath) {
106
- let parser;
107
- if (relPath === '') {
108
- parser = path_1.default.join(path_1.default.resolve('.'), 'src/impl/parser');
109
- }
110
- else {
111
- const resolvedPlugin = require.resolve('@sap/eslint-plugin-cds', { paths: [path_1.default.resolve(relPath)] });
112
- parser = path_1.default.join(path_1.default.dirname(resolvedPlugin), 'parser');
113
- }
114
- return new eslint_1.RuleTester({ parser });
115
- }
116
- exports.getRuleTester = getRuleTester;
117
- //# sourceMappingURL=ruleFactory.js.map
1
+ /**
2
+ * Rule report object (as prescribed by ESLint):
3
+ * https://eslint.org/docs/developer-guide/working-with-rules
4
+ *
5
+ * Each ESLint rule module must be composed of a 'meta', 'create' object:
6
+ * - 'meta': meta data for rule (docs, fixable, etc.)
7
+ * - 'create': ingests rule context and returns object with nodes to visit
8
+ * while traversing the AST
9
+ *
10
+ * Since we want to lint cds models without an AST, we adapted the context
11
+ * object to explicitly pass some additional information:
12
+ * - 'code': code object based on ESLint getFromSourceCode()
13
+ * - 'filePath': ESLint getFilename()
14
+ * - 'model': Loaded cds model (CSN)
15
+ * - 'cds': Proxy for cached cds calls
16
+ *
17
+ * @typedef { import('eslint').Rule.RuleModule } RuleModule
18
+ * @typedef { import('eslint').Rule.RuleContext } RuleContext
19
+ * @typedef { import('eslint').Rule.Node } RuleNode
20
+ * @typedef { import("./types").CDSRuleSpec } CDSRuleSpec
21
+ * @typedef { import("./types").CDSRuleMetaData } CDSRuleMetaData
22
+ * @typedef { import("./types").CDSRuleContext } CDSRuleContext
23
+ * @typedef { import("./types").CDSRuleTestOpts } CDSRuleTestOpts
24
+ */
25
+
26
+ const fs = require("fs");
27
+ const path = require("path");
28
+ const { RuleTester, SourceCode } = require("eslint");
29
+ const { isEditor, isValidFile, hasCompilationError, isTest } = require("./utils/helpers");
30
+ const { isValidModel, isValidEnv, isValidRule } = require("./utils/validate");
31
+ const { Cache, getAST, updateCache } = require("./utils/model");
32
+ const { checkDisabled, getRules } = require("./utils/rules");
33
+ const { customRulesDir, categories } = require("./constants");
34
+
35
+ /**
36
+ * Wrapper for ESLint's Rule creator:
37
+ * https://eslint.org/docs/developer-guide/working-with-rules
38
+ * - Must follow the ESLint prescribed convention for all rule exports
39
+ * - ESLint uses 'create' function to traverse its AST nodes
40
+ * - Since we do not work with an AST for cds models, a dummy 'Programm'
41
+ * node is used as an entry point
42
+ * - For all ESLint rules, we have two entry points for additional checks:
43
+ * 1. Before ESLint's rule creation via create()
44
+ * (see below)
45
+ * 2. Before ESLint's report via context.report()
46
+ * (see getProxyReport())
47
+ * @param {CDSRuleSpec} spec
48
+ * @returns {RuleModule}
49
+ */
50
+ function createRule(spec) {
51
+ const { meta, create } = spec;
52
+ if (!meta.type) meta.type = "problem";
53
+ if (meta.docs && !meta.docs.category) meta.docs.category = categories["model"];
54
+ return {
55
+ meta,
56
+ create: function (context) {
57
+ return {
58
+ Program: function (node) {
59
+ // --- Checks before create() ---
60
+ // If plugin rules have been loaded
61
+ if (Cache.has("rulesInfo")) {
62
+ let { listEnvRules, listModelRules, listRules } = Cache.get("rulesInfo");
63
+ let cdscontext = createCDSContext(context, node, listEnvRules, listModelRules, listRules);
64
+
65
+ // If file has plugin's allowed extension or a valid environment
66
+ if (isValidFile(cdscontext.filePath) || isValidEnv(cdscontext.options)) {
67
+ cdscontext = updateCache(cdscontext);
68
+
69
+ // If rule has not already been evaluated for this model
70
+ if (!Cache.get(`done:${cdscontext.configPath}:${cdscontext.ruleID}` === cdscontext.filePath)) {
71
+ let customRulesPath = path.join(Cache.get(`configpath`), customRulesDir, "rules");
72
+ const stats = fs.statSync(Cache.get("configpath"));
73
+ if (stats.isFile()) {
74
+ customRulesPath = path.join(Cache.get('projectpath'), customRulesDir, "rules");
75
+ }
76
+ let customRulesInfo;
77
+ if (fs.existsSync(customRulesPath)) {
78
+ customRulesInfo = getRules(customRulesPath);
79
+ listEnvRules = listEnvRules.concat(customRulesInfo.listEnvRules);
80
+ listModelRules = listModelRules.concat(customRulesInfo.listModelRules);
81
+ }
82
+
83
+ // If valid rule and model/env
84
+ if (
85
+ isValidRule(cdscontext, listEnvRules) ||
86
+ (isValidRule(cdscontext, listModelRules) &&
87
+ isValidModel(cdscontext) &&
88
+ !hasCompilationError(cdscontext))
89
+ ) {
90
+ create(cdscontext);
91
+ Cache.set(`done:${cdscontext.configPath}:${cdscontext.ruleID}`, cdscontext.filePath);
92
+
93
+ // If compilation error (only shown on console, not in editor)
94
+ } else if (hasCompilationError(cdscontext) && !isEditor()) {
95
+ create(cdscontext);
96
+ }
97
+ }
98
+ }
99
+ }
100
+ },
101
+ };
102
+ },
103
+ };
104
+ }
105
+
106
+ /**
107
+ * Generates proxy for ESLint's context object which adds caching
108
+ * @param obj ESLint's context object
109
+ * @returns Proxy for cds
110
+ */
111
+ function getProxyReport(obj) {
112
+ const handler = {
113
+ get(target, prop, receiver) {
114
+ const value = Reflect.get(target, prop, receiver);
115
+ if (typeof value !== "object") {
116
+ return value;
117
+ }
118
+ /* eslint no-extra-boolean-cast: "off" */
119
+ if (!!value) {
120
+ return new Proxy(value, handler);
121
+ }
122
+ return {
123
+ err: `Property ${prop} prop does not exist on object ${obj}!`,
124
+ };
125
+ },
126
+ apply(target, thisArg, argumentsList) {
127
+ let report = false;
128
+ if (argumentsList.length > 0) {
129
+ argumentsList.forEach((lint) => {
130
+ if (lint) {
131
+ // --- Checks before context.report() ---
132
+ let { listEnvRules, listModelRules, listRules } = Cache.get("rulesInfo");
133
+
134
+ // If rule/loc not disabled by ESLint disable comment
135
+ if (!checkDisabled(lint, thisArg, listRules, listEnvRules, listModelRules)) {
136
+ const fileRel = lint.file;
137
+ let fileAbs = lint.file || "";
138
+ if (!path.isAbsolute(fileAbs)) {
139
+ fileAbs = fileRel ? path.join(Cache.get("configpath"), fileRel) : "";
140
+ }
141
+ const stats = fs.statSync(Cache.get("configpath"));
142
+ if (stats.isFile()) {
143
+ fileAbs = Cache.get("configpath");
144
+ }
145
+
146
+ // If environment rule, only report once per configPath
147
+ if (
148
+ listEnvRules.includes(thisArg.ruleID) ||
149
+ listEnvRules.includes(thisArg.ruleID.replace("@sap/cds/", ""))
150
+ ) {
151
+ if (!isEditor()) {
152
+ if (!Cache.has(`envChecks:${thisArg.configPath}`)) {
153
+ report = true;
154
+ Cache.set(`envChecks:${thisArg.configPath}`, [lint.message]);
155
+ } else if (
156
+ Cache.has(`envChecks:${thisArg.configPath}`) &&
157
+ !Cache.get(`envChecks:${thisArg.configPath}`).includes(lint.message)
158
+ ) {
159
+ report = true;
160
+ Cache.set(`envChecks:${thisArg.configPath}`, [lint.message]);
161
+ }
162
+ }
163
+
164
+ // If model rules, only report if file matches that of report
165
+ } else if (
166
+ fileAbs === thisArg.filePath ||
167
+ fileAbs === thisArg.configPath ||
168
+ fileRel === "<stdin>.cds" ||
169
+ isTest()
170
+ ) {
171
+ report = true;
172
+ }
173
+ if (report) {
174
+ return thisArg._context.report(lint);
175
+ }
176
+ }
177
+ }
178
+ });
179
+ }
180
+ },
181
+ };
182
+ return new Proxy(obj, handler);
183
+ }
184
+
185
+ /**
186
+ * Experimental wrapper for 'createRule' to yield:
187
+ * - More eslint-like API
188
+ * - More convenience re error reports
189
+ * @param {CDSRuleSpec} spec
190
+ * @returns {RuleModule}
191
+ */
192
+ function defineRule(spec) {
193
+ const { meta, create } = spec;
194
+ if (!meta.type) meta.type = "problem";
195
+ if (meta.docs && !meta.docs.category) meta.docs.category = "Model Validation";
196
+ return createRule({
197
+ meta,
198
+ create: (context) => {
199
+ const { cds, report } = context;
200
+ const handlers = create({
201
+ cds,
202
+ model: cds.model,
203
+ report: (r) => report(r),
204
+ });
205
+ if (cds.model) {
206
+ cds.model.forall((d) => {
207
+ for (let each in handlers)
208
+ if (d.is(each)) {
209
+ let r = handlers[each](d);
210
+ if (r) {
211
+ if (typeof r === "string") r = { message: r };
212
+ if (!r.loc) r.loc = cds.getLocation(d.name, d);
213
+ if (!r.file) r.file = (d.$location && d.$location.file) || "unknown.cds";
214
+ context.report(r);
215
+ }
216
+ }
217
+ });
218
+ }
219
+ },
220
+ });
221
+ }
222
+
223
+ /**
224
+ * Expands CDS context object with some CDS properties
225
+ * We also retrieve the file contents cached by the preprocessor
226
+ * @param {RuleContext} context
227
+ * @param {RuleNode} node
228
+ * @returns cdscontext
229
+ */
230
+ function createCDSContext(context, node, envRules, modelRules, rules) {
231
+ let sourcecode = context.getSourceCode();
232
+ let code = sourcecode.getText(node);
233
+ if (!code) {
234
+ code = Cache.get(`processed:${context.getPhysicalFilename()}`);
235
+ }
236
+ if (code) {
237
+ sourcecode = new SourceCode(code, getAST(code));
238
+ }
239
+ return {
240
+ _context: context,
241
+ ...context,
242
+ cds: context.parserServices.cdsProxy || Cache.get("cds"),
243
+ configPath: Cache.get("configpath"),
244
+ code,
245
+ filePath: context.getPhysicalFilename(),
246
+ options: context.options,
247
+ ruleID: context.id,
248
+ sourcecode,
249
+ envRules,
250
+ modelRules,
251
+ node,
252
+ rules,
253
+ report: getProxyReport(context.report),
254
+ };
255
+ }
256
+
257
+ /**
258
+ * ESLint RuleTester (used by custom rule creator api)
259
+ * Calls ESLint's RuleTester with custom cds parser and input for
260
+ * valid/invalid checks:
261
+ * Model checks require input 'code' entries
262
+ * Env checks require input 'options' with selected parameters
263
+ * @param {CDSRuleTestOpts} options RuleTester input options
264
+ * @returns RuleTester results
265
+ */
266
+ function runRuleTester(options) {
267
+ let parser;
268
+ let rule = {};
269
+ const rulename = path.basename(options.root);
270
+ const plugin = "eslint-plugin-cds";
271
+ if (options.root.includes(plugin)) {
272
+ // For plugin's internal tests, resolve parser from here
273
+ parser = require.resolve("./parser");
274
+ rule = require(`./rules/${path.basename(options.root)}`);
275
+ Cache.set("rulesInfo", getRules(path.join(path.dirname(options.root), "../../lib/impl/rules")));
276
+ } else {
277
+ // Otherwise from project root
278
+ const resolvedPlugin = require.resolve("@sap/eslint-plugin-cds", {
279
+ paths: [options.root],
280
+ });
281
+ parser = path.join(path.dirname(resolvedPlugin), "parser");
282
+ rule = require(path.join(options.root, `../../rules/${path.basename(options.root)}`));
283
+ Cache.set("rulesInfo", getRules(path.join(options.root, "../../rules")));
284
+ }
285
+ let category = categories["model"];
286
+ if (rule.meta) {
287
+ category = rule.meta.docs.category;
288
+ }
289
+ let tester = new RuleTester({});
290
+ if (parser) {
291
+ tester = new RuleTester({ parser });
292
+ }
293
+ const testerCases = {};
294
+ ["valid", "invalid"].forEach((type) => {
295
+ const filePath = path.join(options.root, `${type}/${options.filename}`);
296
+ testerCases[type] = [
297
+ {
298
+ filename: filePath,
299
+ },
300
+ ];
301
+ if (category === "Environment") {
302
+ testerCases[type][0].code = "";
303
+ testerCases[type][0].options = [{ environment: JSON.parse(fs.readFileSync(filePath, "utf8")) }];
304
+ } else if (!category || category === categories.model) {
305
+ testerCases[type][0].code = fs.readFileSync(filePath, "utf8");
306
+ }
307
+ if (type === "invalid") {
308
+ testerCases[type][0].errors = options.errors;
309
+ const fileFixed = path.join(options.root, `fixed/${options.filename}`);
310
+ if (fs.existsSync(fileFixed)) {
311
+ testerCases[type][0].output = fs.readFileSync(fileFixed, "utf8");
312
+ }
313
+ }
314
+ });
315
+ return tester.run(rulename, rule, testerCases);
316
+ }
317
+
318
+ module.exports = { createRule, defineRule, runRuleTester };
319
+