@sap/eslint-plugin-cds 2.4.1 → 2.5.0

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.
Files changed (48) hide show
  1. package/CHANGELOG.md +16 -2
  2. package/lib/api/index.js +9 -8
  3. package/lib/conf/all.js +21 -0
  4. package/lib/conf/index.js +22 -0
  5. package/lib/conf/recommended.js +18 -0
  6. package/lib/constants.js +10 -8
  7. package/lib/index.js +11 -32
  8. package/lib/parser.js +158 -7
  9. package/lib/rules/assoc2many-ambiguous-key.js +21 -38
  10. package/lib/rules/auth-no-empty-restrictions.js +13 -21
  11. package/lib/rules/auth-use-requires.js +15 -15
  12. package/lib/rules/auth-valid-restrict-grant.js +71 -34
  13. package/lib/rules/auth-valid-restrict-keys.js +22 -16
  14. package/lib/rules/auth-valid-restrict-to.js +71 -27
  15. package/lib/rules/auth-valid-restrict-where.js +24 -15
  16. package/lib/rules/index.js +26 -0
  17. package/lib/rules/latest-cds-version.js +8 -7
  18. package/lib/rules/min-node-version.js +10 -9
  19. package/lib/rules/no-db-keywords.js +16 -15
  20. package/lib/rules/no-dollar-prefixed-names.js +9 -7
  21. package/lib/rules/no-join-on-draft-enabled-entities.js +9 -24
  22. package/lib/rules/require-2many-oncond.js +9 -14
  23. package/lib/rules/sql-cast-suggestion.js +6 -20
  24. package/lib/rules/start-elements-lowercase.js +5 -8
  25. package/lib/rules/start-entities-uppercase.js +8 -11
  26. package/lib/rules/valid-csv-header.js +66 -66
  27. package/lib/{api/lint.d.ts → types.d.ts} +4 -7
  28. package/lib/utils/Cache.js +33 -0
  29. package/lib/utils/Colors.js +9 -0
  30. package/lib/utils/createRule.js +304 -0
  31. package/lib/utils/createRuleDocs.js +361 -0
  32. package/lib/utils/{fuzzySearch.js → findFuzzy.js} +0 -2
  33. package/lib/utils/genDocs.js +363 -0
  34. package/lib/utils/getConfigPath.js +33 -0
  35. package/lib/utils/getConfiguredFileTypes.js +10 -0
  36. package/lib/utils/getFileExtensions.js +8 -0
  37. package/lib/utils/isConfiguredFileType.js +20 -0
  38. package/lib/utils/jsonc.js +1 -1
  39. package/lib/utils/jsoncParser.js +1 -0
  40. package/lib/utils/rules.js +112 -1041
  41. package/lib/utils/runRuleTester.js +111 -0
  42. package/package.json +4 -4
  43. package/lib/processor.js +0 -50
  44. package/lib/utils/helpers.js +0 -94
  45. package/lib/utils/model.js +0 -393
  46. package/lib/utils/ruleHelpers.js +0 -199
  47. package/lib/utils/ruleTester.js +0 -78
  48. package/lib/utils/validate.js +0 -36
@@ -0,0 +1,111 @@
1
+ const fs = require("fs");
2
+ const path = require("path");
3
+
4
+ const { RuleTester } = require("eslint");
5
+ const Cache = require("./Cache");
6
+ const createRule = require("./createRule");
7
+ const isConfiguredFileType = require("./isConfiguredFileType");
8
+ const { compileModelFromDict } = require("../parser");
9
+
10
+ /**
11
+ * ESLint RuleTester (used by custom rule creator api)
12
+ * Calls ESLint's RuleTester with custom cds parser and input for
13
+ * valid/invalid checks:
14
+ * Model checks require input 'code' entries
15
+ * Env checks require input 'options' with selected parameters
16
+ * @param {CDSRuleTestOpts} options RuleTester input options
17
+ * @returns RuleTester results
18
+ */
19
+ module.exports = (options) => {
20
+ let parser;
21
+ let rule = {};
22
+ Cache.set("rules", require(path.join(__dirname, "../rules")));
23
+ const rulename = path.basename(options.root);
24
+ if (options.root.startsWith(path.resolve(__dirname, "../.."))) {
25
+ // For plugin's internal tests, resolve parser from here
26
+ parser = require.resolve("../parser");
27
+ const pluginPath = path.join(path.dirname(options.root), "../..");
28
+ rule = createRule(require(`../rules/${path.basename(options.root)}`));
29
+ Cache.set("pluginpath", pluginPath);
30
+ } else {
31
+ // Otherwise from project root
32
+ const resolvedPlugin = require.resolve("@sap/eslint-plugin-cds", {
33
+ paths: [options.root],
34
+ });
35
+ parser = path.join(path.dirname(resolvedPlugin), "parser");
36
+ rule = require(path.join(options.root, `../rules/${path.basename(options.root)}`));
37
+ const pluginPath = path.join(path.dirname(options.root), "../../..");
38
+ Cache.set("pluginpath", pluginPath);
39
+ }
40
+ let tester = new RuleTester({});
41
+ if (parser) {
42
+ tester = new RuleTester({ parser });
43
+ }
44
+ const testerCases = {};
45
+ ["valid", "invalid"].forEach((type) => {
46
+ const filePath = path.join(options.root, `${type}/${options.filename}`);
47
+ Cache.set("rootpath", path.dirname(filePath));
48
+ _initModelRuleTester(filePath);
49
+ testerCases[type] = [
50
+ {
51
+ filename: filePath,
52
+ },
53
+ ];
54
+ if (!isConfiguredFileType(options.filename, "FILES")) {
55
+ const fileContents = JSON.parse(fs.readFileSync(filePath, "utf8"));
56
+ testerCases[type][0].code = "";
57
+ testerCases[type][0].filename = "<text>";
58
+ testerCases[type][0].options = [{ environment: fileContents }];
59
+ } else {
60
+ testerCases[type][0].code = fs.readFileSync(filePath, "utf8");
61
+ if (options.options) {
62
+ testerCases[type][0].options = options.options;
63
+ }
64
+ }
65
+ if (type === "invalid") {
66
+ testerCases[type][0].errors = options.errors;
67
+ const fileFixed = path.join(options.root, `fixed/${options.filename}`);
68
+ if (fs.existsSync(fileFixed) && rule.meta.type !== "suggestion") {
69
+ testerCases[type][0].output = fs.readFileSync(fileFixed, "utf8");
70
+ }
71
+ }
72
+ });
73
+ return tester.run(rulename, rule, testerCases);
74
+ }
75
+
76
+ /**
77
+ * Creates a model for ESLint unit tests
78
+ */
79
+ function _initModelRuleTester(filePath) {
80
+ Cache.set("test", true);
81
+ const rootPath = path.dirname(filePath);
82
+ Cache.set("rootpath", rootPath);
83
+ let files = fs.readdirSync(rootPath);
84
+ const modelfiles = files.map((f) => path.join(rootPath, f)).filter((fp) => isConfiguredFileType(fp, "MODEL_FILES"));
85
+ Cache.set(`modelfiles:${rootPath}`, modelfiles);
86
+ const dictFiles = _getDictFiles(rootPath, modelfiles);
87
+ Cache.set(`dictfiles:${rootPath}`, dictFiles);
88
+ const reflectedModel = compileModelFromDict(dictFiles);
89
+ Cache.set(`model:${rootPath}`, reflectedModel);
90
+ }
91
+
92
+ /**
93
+ * Creates or updates a dictionary of files/file contents for a given
94
+ * project path.
95
+ * @param input
96
+ * @param files
97
+ * @returns dictFiles
98
+ */
99
+ function _getDictFiles(input, files) {
100
+ let dictFiles = {};
101
+ if (Cache.has(`dictfiles:${input}`)) {
102
+ dictFiles = Cache.get(`dictfiles:${input}`);
103
+ } else {
104
+ files.forEach((file) => {
105
+ dictFiles[file] = Cache.has(`file:${file}`)
106
+ ? Cache.get(`file:${file}`)
107
+ : fs.readFileSync(file, "utf8")
108
+ });
109
+ }
110
+ return dictFiles;
111
+ }
package/package.json CHANGED
@@ -1,14 +1,14 @@
1
1
  {
2
2
  "name": "@sap/eslint-plugin-cds",
3
- "version": "2.4.1",
3
+ "version": "2.5.0",
4
4
  "description": "ESLint plugin including recommended SAP Cloud Application Programming model and environment rules",
5
5
  "homepage": "https://cap.cloud.sap/",
6
6
  "keywords": [
7
7
  "eslint",
8
- "eslintplugin",
9
- "typescript",
8
+ "eslint-plugin",
10
9
  "cds",
11
- "cds-lint"
10
+ "cds-lint",
11
+ "cds-lint-plugin"
12
12
  ],
13
13
  "author": "SAP SE (https://www.sap.com)",
14
14
  "license": "See LICENSE file",
package/lib/processor.js DELETED
@@ -1,50 +0,0 @@
1
- /**
2
- * Custom ESLint 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
- *
8
- * Note, that because we cache the file contents and return files contents,
9
- * the plugin's parser is bypassed so we must retrieve the file contents (see createRule()
10
- * in utils/rules.js).
11
- */
12
-
13
- const { Cache } = require("./utils/model");
14
- const { isValidFile } = require("./utils/helpers");
15
-
16
- module.exports = {
17
- preprocess: function (text, filename) {
18
- if (isValidFile(filename, 'FILES')) {
19
- Cache.set(`file:${filename}`, text);
20
- }
21
- return [{ text: "", filename }];
22
- },
23
- /**
24
- * Returns message objects as defined by ESLint:
25
- * https://eslint.org/docs/developer-guide/working-with-custom-formatters#the-message-object
26
- * @param {*} messages
27
- * @returns
28
- */
29
- postprocess: function (messages) {
30
- const messagesSanitized = [];
31
- messages.forEach(fileMessages => {
32
- const fileMessagesSanitized = [];
33
- fileMessages.forEach(r => {
34
- if (r && r.message && r.message.startsWith(`CompilationError:`)) {
35
- r.message = r.message.replace(`CompilationError: `,
36
- 'CDS model could not be compiled!\n');
37
- r.ruleId = `❗${r.ruleId}`;
38
- r.severity = 2;
39
- }
40
- fileMessagesSanitized.push(r);
41
- })
42
- messagesSanitized.push(fileMessagesSanitized);
43
- })
44
- if (Cache.has("test")) {
45
- Cache.clear();
46
- }
47
- return [].concat(...messagesSanitized);
48
- },
49
- supportsAutofix: true,
50
- };
@@ -1,94 +0,0 @@
1
- const { FILES, MODEL_FILES } = require("../constants");
2
-
3
- module.exports = {
4
- /**
5
- * Checks whether the given filePath matches a regex `files`
6
- * @param {string} filePath
7
- * @returns boolean
8
- */
9
- isValidFile: function (filePath, fileType) {
10
- const genRegex = (key) => new RegExp(`${key.map((file) => file.replace("*", "")).join("$|")}$`);
11
- let isValid = false;
12
- switch(fileType) {
13
- case 'MODEL_FILES':
14
- isValid = genRegex(MODEL_FILES).test(filePath);
15
- break;
16
- case 'FILES':
17
- isValid = genRegex(FILES).test(filePath);
18
- break;
19
- }
20
- return isValid;
21
- },
22
- /**
23
- * Checks whether the plugin is run via VS Code ESLint extension
24
- * @returns boolean
25
- */
26
- isVSCodeEditor() {
27
- return process.argv.join(" ").includes("dbaeumer.vscode-eslint");
28
- },
29
-
30
- /**
31
- * Checks whether ESLint is running in debug mode
32
- * @returns boolean
33
- */
34
- hasDebugFlag() {
35
- return process.argv.includes("--debug");
36
- },
37
-
38
- /**
39
- * Returns an array of allowed file extensions
40
- * the plugin can parse of the form "*.ext"
41
- * @returns {ConfigOverrideFiles} Array of file extensions
42
- */
43
- getFileExtensions: function() {
44
- return FILES;
45
- },
46
-
47
- /**
48
- * Attempts to extract JSON from a text by looking for the longst substring
49
- * enclosed by braces or brackets. Input string can therefore either contain
50
- * a JSON object enclosed by braces, or a JSON array enclosed by brackets.
51
- * No semantic parsing is done whatsoever (aside from the final JSON.parse)
52
- * so if the input string is not sane, you will only notice from the
53
- * final parse step failing.
54
- * @param text text from which to extract JSON.
55
- * @param index the start index of the first opening "{" or "[" within text.
56
- * @returns a parsed JSON object or an empty object if not called with proper parameters.
57
- * @throws Errors when JSON contained within string is not valid.
58
- */
59
- extractJSON: function(text, index) {
60
- const [opening, closing] = {
61
- "{": ["{", "}"],
62
- "[": ["[", "]"],
63
- }[text[index]] || [undefined, undefined];
64
-
65
- // neither "[" nor "{" at beginning -> fail fast
66
- if (opening === undefined) return {};
67
-
68
- // we expect caller to call with an index of the first opening brace.
69
- // So add that brace and increment index at start.
70
- index++;
71
- let result = opening;
72
- let open = 1;
73
- while (open > 0 && index < text.length) {
74
- const char = text[index];
75
- if (char === closing) {
76
- open--;
77
- } else if (char === opening) {
78
- open++;
79
- }
80
-
81
- result += char;
82
- index++;
83
- }
84
-
85
- if (open !== 0) {
86
- throw new Error(
87
- "text does not contain proper JSON (unmatched opening or closing brace)"
88
- );
89
- }
90
-
91
- return JSON.parse(result);
92
- }
93
-
94
- };
@@ -1,393 +0,0 @@
1
- /**
2
- * @typedef { import("eslint").AST.SourceLocation } SourceLocation
3
- */
4
-
5
-
6
- const fs = require("fs");
7
- const path = require("path");
8
- const cds = require("@sap/cds");
9
- const { SourceCode } = require("eslint");
10
- const { isValidFile } = require("./helpers");
11
-
12
- const cache = new Map();
13
-
14
- module.exports = {
15
- /**
16
- * Simple cache to store model and any cds calls made in the rule creation
17
- * api to modify the model
18
- */
19
- Cache: {
20
- has(key) {
21
- return cache.has(key);
22
- },
23
- set(key, value) {
24
- return cache.set(key, [value, Date.now()]);
25
- },
26
- get(key) {
27
- return cache.get(key) ? cache.get(key)[0] : undefined
28
- },
29
- dump() {
30
- const dump = {};
31
- for (const [key, value] of cache.entries()) {
32
- const timestamp = new Date(value[1]);
33
- dump[key] = { key, value: JSON.stringify(value[0]), timestamp };
34
- }
35
- return dump;
36
- },
37
- remove(key) {
38
- if (cache.has(key)) {
39
- cache.delete(key);
40
- }
41
- },
42
- clear() {
43
- cache.clear();
44
- },
45
- },
46
-
47
- /**
48
- * Checks whether the path where the nearest ESLint configuration
49
- * file has changed
50
- * @param {*} configPath
51
- * @returns boolean
52
- */
53
- isNewConfigPath: function (configPath) {
54
- return !module.exports.Cache.has("configpath")
55
- && (configPath !== module.exports.Cache.get("configpath"))
56
- },
57
-
58
- /**
59
- * Gets directory of the nearest ESLint config files associated
60
- * Within this plugin, this is equivalent to the cds project's directory
61
- * @param filePath
62
- * @returns Directory of ESLint config file
63
- */
64
- loadConfigPath: function (filePath) {
65
- let configPath = path.dirname(module.exports.getConfigPath(filePath));
66
- if (configPath) {
67
- module.exports.Cache.set("configpath", configPath);
68
- } else {
69
- throw new Error("Failed to find an ESLint configuration file!");
70
- }
71
- return configPath;
72
- },
73
-
74
- /**
75
- * Generates dummy AST with just single Program node
76
- * @param code Parse file contents
77
- * @returns AST
78
- */
79
- getAST: function (code) {
80
- return {
81
- type: "Program",
82
- body: [],
83
- sourceType: "module",
84
- tokens: [],
85
- comments: [],
86
- range: [0, code.length],
87
- loc: {
88
- start: {
89
- line: 1,
90
- column: 0,
91
- },
92
- end: {
93
- line: 1,
94
- column: 0,
95
- },
96
- },
97
- };
98
- },
99
-
100
- /**
101
- * Converts code with {line, column} to ESLint's 'range' property:
102
- * https://eslint.org/docs/developer-guide/working-with-custom-parsers#all-nodes
103
- * code.slice(node.range[0], node.range[1]) must be the text of the node!
104
- * @param code source code
105
- * @param line line number
106
- * @param column column number
107
- * @returns ESLint range
108
- */
109
- getRange: function (code, line, column) {
110
- const lines = typeof code === "string" ? SourceCode.splitLines(code) : code
111
- const ranges = [0];
112
- lines.forEach((line, i) => {
113
- ranges[i + 1] = i === 0 ? line.length + 1 : ranges[i] + line.length + 1
114
- });
115
- return line > 1 ? ranges[line - 1] + column : column
116
- },
117
-
118
- /**
119
- * Uses ESLint's static function splitLines() to split the source code text
120
- * into an array of lines:
121
- * https://eslint.org/docs/developer-guide/nodejs-api#sourcecodesplitlines
122
- * Returns the index of the last line
123
- * @param code
124
- * @returns Last line index
125
- */
126
- getLastLine: function (code) {
127
- const lines = typeof code === "string" ? SourceCode.splitLines(code) : code
128
- return lines.length - 1;
129
- },
130
-
131
- /**
132
- * Generates ESlint's 'loc' from artifact string and cds $location property:
133
- * https://eslint.org/docs/developer-guide/working-with-rules-deprecated#contextreport
134
- * @param name
135
- * @param {SoureLocation} obj
136
- * @returns ESLint's 'loc' object
137
- */
138
- getLocation: function (name, obj, model) {
139
- let loc;
140
- const defaultLoc = {
141
- start: { line: 0, column: 0 },
142
- end: { line: 1, column: 0 },
143
- };
144
- if (obj.$location) {
145
- const nameloc = obj.$location;
146
- if (nameloc) {
147
- // CSN entry with column 0 is equivalent to 'undefined'
148
- // It means that the column in that line cannot be determined,
149
- // so we assign a value 1 to get a column location of 0
150
- if (nameloc.col === 0) {
151
- nameloc.col = 1;
152
- }
153
- loc = defaultLoc;
154
- loc.start.column = nameloc.col - 1;
155
- loc.start.line = nameloc.line;
156
- loc.end.column = nameloc.col - 1 + name.length;
157
- loc.end.line = nameloc.line;
158
- } else if (obj.parent) {
159
- this.getLocation(name, obj.parent, model);
160
- }
161
- }
162
- // Empty locations default to line 0, column 0
163
- if (!loc) {
164
- loc = defaultLoc;
165
- }
166
- return loc;
167
- },
168
-
169
- /**
170
- * Searches for ESLint config file types (in order or precedence)
171
- * and returns corresponding directory (usually project's root dir)
172
- * https://eslint.org/docs/user-guide/configuring#configuration-file-formats
173
- * @param {string} currentDir start here and search until root dir
174
- * @returns {string} dir containing ESLint config file (empty if not exists)
175
- */
176
- getConfigPath: function (currentDir = ".") {
177
- const configFiles = [
178
- ".eslintrc.js",
179
- ".eslintrc.cjs",
180
- ".eslintrc.yaml",
181
- ".eslintrc.yml",
182
- ".eslintrc.json",
183
- ".eslintrc",
184
- "package.json",
185
- ];
186
- let configDir = path.resolve(currentDir);
187
- while (configDir !== path.resolve(configDir, "..")) {
188
- for (let i = 0; i < configFiles.length; i++) {
189
- const configPath = path.join(configDir, configFiles[i]);
190
- if (fs.existsSync(configPath) && fs.statSync(configPath).isFile()) {
191
- return configPath;
192
- }
193
- }
194
- configDir = path.join(configDir, "..");
195
- }
196
- return "";
197
- },
198
-
199
- /**
200
- * Compiles reflected model for a given project directory
201
- * Note, that to support monorepos, the cache (in @sap/cds) must be cleared
202
- * to also change the roots with every changed configPath.
203
- * @param configPath
204
- * @returns reflected model
205
- */
206
- compileModelFromPath: function (configPath) {
207
- let compiledModel;
208
- let reflectedModel;
209
- cds.resolve.cache = {};
210
- const roots = cds.resolve("*", { root: configPath });
211
- const messages = [];
212
- if (roots) {
213
- try {
214
- compiledModel = cds.load(roots, {
215
- cwd: configPath,
216
- sync: true,
217
- locations: true,
218
- messages,
219
- });
220
- module.exports.Cache.remove('errRootModel');
221
- } catch (err) {
222
- module.exports.Cache.set('errRootModel', err);
223
- }
224
- if (compiledModel) {
225
- reflectedModel = cds.linked(compiledModel);
226
- if (messages) {
227
- reflectedModel.messages = messages;
228
- }
229
- }
230
- }
231
- return reflectedModel;
232
- },
233
-
234
- /**
235
- * Compiles reflected model for a dictionary of files/file contents
236
- * Note, that this method is used to account for editor type events
237
- * and hence, model updates.
238
- * WARNING: Only use if cds roots are defined prior to this step
239
- * and the dictionary is complete (the compiler will not resolve
240
- * any missing files)!
241
- * @param dictFiles
242
- * @returns reflected model
243
- */
244
- compileModelFromDict: function (dictFiles, options) {
245
- let reflectedModel;
246
- const messages = [];
247
- const compiledModel = cds.compile(dictFiles, {
248
- sync: true,
249
- locations: true,
250
- messages,
251
- ...options,
252
- });
253
- if (compiledModel) {
254
- reflectedModel = cds.linked(compiledModel);
255
- if (messages) {
256
- reflectedModel.messages = messages;
257
- }
258
- }
259
- return reflectedModel;
260
- },
261
-
262
- compileModelFromFile: function (code, filePath) {
263
- let compiledModel;
264
- let reflectedModel;
265
- const dictFiles = {};
266
- dictFiles[filePath] = code;
267
- let flavor = "inferred";
268
- try {
269
- compiledModel = module.exports.compileModelFromDict(dictFiles, {
270
- flavor,
271
- });
272
- } catch (err) {
273
- // Supress errors from parked files
274
- }
275
- if (compiledModel) {
276
- reflectedModel = cds.linked(compiledModel);
277
- }
278
- return reflectedModel;
279
- },
280
-
281
- /**
282
- * Initiates and stores new reflected model, it's corresponding project path,
283
- * as well as a list and dictionary of files comprising the model.
284
- * @param configPath
285
- * @param filePath
286
- */
287
- initRootModel: function (configPath) {
288
- module.exports.Cache.set("configpath", configPath);
289
- const reflectedModel = module.exports.compileModelFromPath(configPath);
290
- module.exports.Cache.set(`model:${configPath}`, reflectedModel);
291
- let files;
292
- if (reflectedModel && reflectedModel.$sources) {
293
- files = reflectedModel.$sources;
294
- if (files) {
295
- module.exports.Cache.set(`modelfiles:${configPath}`, files);
296
- } else {
297
- files = [];
298
- }
299
- const dictFiles = module.exports.getDictFiles(configPath, files);
300
- module.exports.Cache.set(`dictfiles:${configPath}`, dictFiles);
301
- }
302
- return reflectedModel;
303
- },
304
-
305
- /**
306
- * Creates a model for ESLint unit tests
307
- */
308
- initModelRuleTester: function (filePath) {
309
- module.exports.Cache.set("test", true);
310
- const configPath = path.dirname(filePath);
311
- module.exports.Cache.set('configpath', configPath);
312
- let files = fs.readdirSync(configPath);
313
- const modelfiles = files.map(f => path.join(configPath, f))
314
- .filter(fp => isValidFile(fp, 'MODEL_FILES'))
315
- module.exports.Cache.set(`modelfiles:${configPath}`, modelfiles);
316
- const dictFiles = module.exports.getDictFiles(configPath, modelfiles);
317
- module.exports.Cache.set(`dictfiles:${configPath}`, dictFiles);
318
- const reflectedModel = module.exports.compileModelFromDict(dictFiles);
319
- module.exports.Cache.set(`model:${configPath}`, reflectedModel);
320
- },
321
-
322
- /**
323
- * Creates or updates a dictionary of files/file contents for a given
324
- * project path.
325
- * @param configPath
326
- * @param files
327
- * @returns dictFiles
328
- */
329
- getDictFiles: function (input, files = []) {
330
- let dictFiles = {};
331
- if (module.exports.Cache.has(`dictfiles:${input}`)) {
332
- dictFiles = module.exports.Cache.get(`dictfiles:${input}`);
333
- } else {
334
- files.forEach((file) => {
335
- dictFiles[file] = module.exports.Cache.has(`file:${file}`)
336
- ? module.exports.Cache.get(`file:${file}`)
337
- : fs.readFileSync(file, "utf8")
338
- });
339
- }
340
- return dictFiles;
341
- },
342
-
343
- /**
344
- * Determines whether an incoming file has changed contents
345
- * @param context cds context object
346
- * @returns boolean
347
- */
348
- hasFileChanged: function (code, filePath, configPath) {
349
- let result = false
350
- const files = module.exports.Cache.get(`modelfiles:${configPath}`);
351
- const dictFiles = module.exports.getDictFiles(configPath, files);
352
- const isFileInModel = module.exports.isFileInModel(filePath, configPath);
353
- // If incoming file is a 'model' file
354
- if (isFileInModel) {
355
- // Only update on detected changes
356
- if (dictFiles[filePath] !== code) {
357
- result = true
358
- }
359
- } else if (dictFiles[filePath] !== code) {
360
- result = true
361
- }
362
- return result;
363
- },
364
-
365
- /**
366
- * Checks whether a file is part of the model for a given project
367
- * @param context
368
- * @param files
369
- * @returns boolean
370
- */
371
- isFileInModel(filePath, configPath) {
372
- let files = module.exports.Cache.get(`modelfiles:${configPath}`) || [];
373
- return files && files.length > 0 && files.includes(filePath)
374
- },
375
-
376
- /**
377
- * Updates and stores reflected model on file changes. Model compilation
378
- * us handled separately for 'model' files (part of model) and 'outsider'
379
- * files.
380
- * @param context cds context object
381
- */
382
- updateModel: function (code, filePath, configPath) {
383
- let reflectedModel;
384
- const dictFiles = module.exports.Cache.get(`dictfiles:${configPath}`);
385
- dictFiles[filePath] = code;
386
- module.exports.Cache.set(`dictfiles:${configPath}`, dictFiles);
387
- reflectedModel = module.exports.compileModelFromDict(dictFiles, { flavor: "inferred" });
388
- if (reflectedModel) { module.exports.Cache.remove('errRootModel') }
389
- module.exports.Cache.set(`model:${configPath}`, reflectedModel);
390
- return reflectedModel;
391
- }
392
-
393
- };